双指针算法:三循环暴力求解,存在重复。
首先将nums排序。
在循环中,first遍历,对于second和third而言,当second和third的值稍小时,second值增加,指针右移,稍大时,third值减小,指针左移,指针运算复杂度为O(n),嵌套first循环,运算复杂度为O(n^2)。排序复杂度为O(n*log(n)),最终计算复杂度为O(n^2)。
官方题解代码:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
nums.sort()
ans = list()
for first in range(n):
if first > 0 and nums[first] == nums[first - 1]:
continue
third = n-1
target = -nums[first]
for second in range(first+1, n):
if second > first + 1 and nums[second] == nums [second - 1]:
continue
while second < third and nums[second] + nums[third] > target:
third -= 1
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first],nums[second],nums[third]])
return ans