15. 3Sum
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]解题要点:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l = i + 1
h = len(nums) - 1
temp = 0 - nums[i]
while l < h:
if nums[l] + nums[h] > temp:
h -= 1
elif nums[l] + nums[h] < temp:
l += 1
else:
res.append([nums[i], nums[l], nums[h]])
while l < h and nums[l] == nums[l+1]: l += 1
while l < h and nums[h] == nums[h-1]: h -= 1
l += 1
h -= 1
return resLast updated