三个数求和:找到和为0的三个数,并且结果中不能有相同的三个数据(虽然在nums是不同位置的数)
参考:https://leetcode.com/problems/3sum/discuss/232712/Best-Python-Solution-(Explained)
主要思路:
(1)对数组排序,时间复杂度:
(2)遍历数组,先固定一个数,如果和上一个数相同的话,就跳过这一步;
(3)固定一个数后,再从两端遍历数组。三个数求和,如大于0则说明right位置的数大了,index左移,如果小于0,说明left位置的数小了,index右移。如果等于0,跳过左边和右边相同的数。
实际上是用了三个指针来解决这个问题的。三个位置的数都跳过了相同的数。
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort() # O(NlogN)
length = len(nums)
for i in range(length - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, length - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
res.append([nums[i], nums[left], nums[right]])
# skip same num
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
return res