三個數求和:找到和爲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