题解 | #三数之和#
三数之和
http://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
- 用双指针的方式,可以减少一次遍历
- 注意代码中重复值的处理
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param num int整型一维数组
# @return int整型二维数组
#
class Solution:
def threeSum(self , num: List[int]) -> List[List[int]]:
# write code here
len_num = len(num)
res = []
if len_num < 3:
return res
num.sort()
for i in range(len_num - 2):
if (i and num[i] == num[i-1]):
continue
left = i + 1
right = len_num - 1
while left < right:
if(num[i] + num[left] + num[right]) ==0:
res.append([num[i], num[left], num[right]])
while(num[left] == num[left + 1] and (left + 1) < right):
left += 1
while(num[right] == num[right - 1] and (right - 1) > left):
right -= 1
left += 1
right -= 1
elif(num[i] + num[left] + num[right] > 0):
right -= 1
else:
left += 1
return res