class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""ans = []n = len(nums)nums = sorted(nums)for first in range(n):if first > 0 and nums[first] == nums[first - 1]:continuetarget = -nums[first]third = n - 1for second in range(first+1, n-1):if second > first+1 and nums[second] == nums[second - 1]:continue# third = n - 1while second < third and nums[second] + nums[third] > target:third -= 1# 跳出while循环了,说明上面肯定有一个条件不满足了if second == third:# continuebreak # second==third,说明没找到符合target的,进行first右移if nums[second] + nums[third] == target:ans.append([nums[first], nums[second], nums[third]])return ans
注意:
- third要放在 for second的外面
- if second == thired要break,说明没有符合target的,要进行for first训练了