【力扣】三数之和
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
我的解题思路:因为要判断三个数,显然不能使用三重循环的暴力解法,通过观察公式,发现通过移项“a+b=-c”可以直遍历两重循环,然后检测-(a+b)是否有对应的c值在nums数组中即可,但是我未解决答案中包含重复三元组的问题,代码如下:
1 class Solution: 2 def threeSum(nums) : 3 a = [] 4 for i in range(len(nums)): 5 for j in range(i+1,len(nums)): 6 if -(nums[i]+nums[j]) in nums and nums.index(-(nums[i]+nums[j])) != i and nums.index(-(nums[i]+nums[j])) != j: 7 a.append([nums[i],nums[j],-(nums[i]+nums[j])]) 8 print(a) 9 return a 10 11 a = Solution.threeSum([-1,0,1,2,-1,-4])
打印的结果:[[-1, 0, 1], [-1, 1, 0], [-1, -1, 2], [0, 1, -1], [0, -1, 1], [1, -1, 0], [2, -1, -1]]
大佬的思路:
排序 + 双指针
本题的难点在于如何去除重复解。
作者:wu_yan_zu
链接:https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
来源:力扣(LeetCode)
算法流程:
1.特判,对于数组长度 $n$,如果数组为 $null$ 或者数组长度小于 3,返回 $[]$。
2.对数组进行排序。
3.遍历排序后数组:
若 $nums[i]>0$,因为已经排序好,所以后面不可能有三个数加和等于 0,直接返回结果。
对于重复元素:跳过,避免出现重复解
令左指针 $L=i+1$,右指针 $R=n-1$,当$L<R$ 时,执行循环:
当 $nums[i]+nums[L]+nums[R]==0$,执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 $L,R$移到下一位置,寻找新的解
若和大于 0,说明 $nums[R]$ 太大,$R$ 左移
若和小于 0,说明 $nums[L]$ 太小,$L$ 右移
1 class Solution: 2 def threeSum(self, nums: List[int]) -> List[List[int]]: 3 4 n=len(nums) 5 res=[] 6 if(not nums or n<3): 7 return [] 8 nums.sort() 9 res=[] 10 for i in range(n): 11 if(nums[i]>0): 12 return res 13 if(i>0 and nums[i]==nums[i-1]): 14 continue 15 L=i+1 16 R=n-1 17 while(L<R): 18 if(nums[i]+nums[L]+nums[R]==0): 19 res.append([nums[i],nums[L],nums[R]]) 20 while(L<R and nums[L]==nums[L+1]): 21 L=L+1 22 while(L<R and nums[R]==nums[R-1]): 23 R=R-1 24 L=L+1 25 R=R-1 26 elif(nums[i]+nums[L]+nums[R]>0): 27 R=R-1 28 else: 29 L=L+1 30 return res 31 32 作者:wu_yan_zu 33 链接:https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/ 34 来源:力扣(LeetCode)
浙公网安备 33010602011771号