[LeetCode]题15:3Sum
第一次解:
res = [] nums.sort() if len(nums)<3:return [] for i in range(len(nums)-2): left = i+1 right = len(nums)-1 while left < right: val = nums[i]+nums[left]+nums[right] if val==0 and [nums[i],nums[left],nums[right]] not in res: res.append([nums[i],nums[left],nums[right]]) elif val<0: left += 1 else: right -=1 return res
超时。。。然后调整
nums.sort() res = [] for i in range(len(nums) - 2): if i > 0 and nums[i-1] == nums[i]: continue l, r = i + 1, len(nums) - 1 while l < r: s = nums[i] + nums[l] + nums[r] if s == 0: res.append([nums[i], nums[l], nums[r]]) l += 1; r -= 1 while l < r and nums[l] == nums[l-1]: l += 1 while l < r and nums[r] == nums[r+1] : r -= 1 elif s < 0: l += 1 else: r -= 1 return res
acc了