思想很简单:排序+三指针
就是要注意怎么减少循环次数,不然疯狂超时。主要考虑到第一个指针指向的值若是已经大于0,就可以结束了;第二个指针和第三个指针当前值若与下一个指向的值相等,也可以直接移动了,不用计算和比较了。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if not nums or n < 3:
return []
nums.sort()
result = []
for first in range(n):
if nums[first] > 0:
return result
if first > 0 and nums[first] == nums[first-1]:
continue
second, third = first+1, n-1
while second < third:
temp_sum = nums[first] + nums[second] + nums[third]
if temp_sum == 0:
result.append([nums[first], nums[second], nums[third]])
while second < third and nums[second] == nums[second+1]:
second += 1
while second < third and nums[third] == nums[third-1]:
third -= 1
second += 1
third -= 1
elif temp_sum > 0:
third -= 1
else:
second += 1
return result
?
|