这题暴力法时间不够,需要进行优化。
先排序是肯定的。
1.最外层遍历所有元素都遍历一次是没问题的,但是要注意两点:1.因为排序了所以nums[i](最外循环的元素)大于0的时候就没有解了,后面都是大的直接break就好。 2.nums[i]和nums[i-1]不能相同,否则就重复了。
2.第二第三层遍历要写成双指针的形式。j从前往后走,k从后往前走,因为每次计算ijk对应元素和target的时候,这个target大于0说明加多了,那么k往前走,小于0说明加的还不够,j往后走。这样能大幅度提升计算速度。
3.同理,每次找到元素后,jk都要找到下一个和自己不同的元素,否则会造成重复。
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: opt = [] if len(nums) < 3: return opt nums.sort() for i in range(len(nums)): if i!=0 and nums[i]==nums[i-1]: continue head = i + 1 tail = len(nums)-1 if nums[i] >0: break while head < tail: target = nums[i]+nums[head]+ nums[tail] if target == 0: opt.append([nums[i],nums[head],nums[tail]]) while head<tail and nums[head]==nums[head+1]: head+=1 while head<tail and nums[tail] == nums[tail-1]: tail-=1 head+=1 tail-=1 elif target < 0: head+=1 else: tail-=1 return opt
原文:https://www.cnblogs.com/snailbuster/p/14588538.html