首先对数据进行排序。
遍历数组,固定三元组中第一个数(i),从后面的数组nums[i+1:]中利用high, low 2个指针,找出和为-nums[i]的所有pair。
对于数组[-1,0,1,2,-1,-4],排序得到[-4,-1,-1,0,1,2]
(1)固定-4,找出[-1,-1,0,1,2]中和为4的数,未找到
(2)固定-1,找出[-1,0,1,2]中和为1的数,找到[-1,2], [0,1]
(3)下一个数是-1,与上一轮中的相同,为了避免重复,跳过
(4)固定0,找出[1,2]中和为0的数,未找到
利用两个指针查找有序数组中和为某个目标值target的方法:首先初始化low, high指针分别指向数组两头,如果nums[low] + nums[high] < target,则low需要向后移;如果nums[low] + nums[high] > target,则high需要向前移动;如果nums[low] + nums[high] = target,则找到一个pair,移动low或者high继续找下一个pair
比如在[-1,-1,0,1,2]中找出和为1的数
(1) low = 0, high = 4
(2) nums[low] + nums[high] = 1,找到[-1,2]
将low加1,此时nums[low]与nums[low-1]相同,为了避免重复,跳过nums[1],再将low加1(low = 2)
(3)nums[low] + nums[high] =2 > 1,将high减1
(4)nums[low] + nums[high] = 1,找到[0,1]
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) <= 2:
return []
nums.sort()
result = []
# 固定第一个数nums[i]
# 利用2 pointer 查找nums[i+1:]中和为-nums[i]的两个数
for i in range(len(nums)-2):
if i-1 >= 0 and nums[i] == nums[i-1]:
continue
low = i + 1
high = len(nums) - 1
while low < high:
# 避免重复的情况
while low < high and nums[low] + nums[high] < -nums[i]:
low += 1
if low >= high:
break
if nums[low] + nums[high] == -nums[i]:
result.append([nums[i], nums[low], nums[high]])
temp = nums[low]
low += 1
# 避免重复的情况
while low < high and nums[low] == temp:
low += 1
while high > low and nums[low] + nums[high] > -nums[i]:
high -= 1
return result