Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
//left自增,right自减 int left = i+1, right = len-1; while(left<right){ int tmp = nums[i]+nums[left]+nums[right]; if(tmp==0){ res.push_back(vector<int>{nums[i], nums[left], nums[right]}); //如果出现数字相同跳过,注意边界条件:left < right while (left < right && nums[left] == nums[left + 1]) left += 1; while (left < right && nums[right] == nums[right - 1]) right -= 1;
classSolution: defthreeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() n = len(nums) res = []
for i in range(n): if res[i] > 0 break if i > 0and nums[i] == nums[i-1]: continue
left = i + 1 right = n - 1 while left < right: cur_sum = nums[i] + nums[left] + nums[right] if cur_sum == 0: tmp = [nums[i],nums[left],nums[right]] res.append(tmp) while left < right and nums[left] == nums[left+1]: left += 1 while left < right and nums[right] == nums[right-1]: right -= 1 left += 1 right -= 1 elif cur_sum > 0: right -= 1 else: left += 1 return res