# Press Shift F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
class Solution(object):
def threeSum(self, nums):
:type nums: List[int]
:rtype: List[List[int]]
双指针法 i为最左指针 L,R分别为次左和右指针
1.先排序
2.最左指针i只用第一个重复数据 所以这里每读到nums[i]与上一个重复时 跨过它
3.对于每一个i进行LR从两边往中间跨步 ****如果三数的和大于0那么将R指针左移 反之右移
4.移步LR指针后先判断是否跟上一个值相同 若相同 继续移步
str_re []
if len(nums) 3:#如果长度小于3直接re
pass
else:#长度大于3
nums.sort()
i_target 1
for i in range(len(nums)):#i即最左指针
if i len(nums)-2:#最左指针不能到倒数第二位
break
elif i_target nums[i]:#i的标记位即nums[i] nums[i-1] 直接进行下一轮循环
continue
elif nums[i] 0:#最左指针不能超过0
return str_re
else:
i_target nums[i]#首先进入循环将i记录下来
L i 1
R len(nums) - 1
R_last L_last None
while L R :#LR指针不能超限
sum nums[L] nums[R] nums[i]
if R_last nums[R]:#如果右指针数值没变继续右移
R- 1
elif L_last nums[L]:#如果左指针数值没变继续左移
elif sum 0:
如果找到了一个解 记录下来 然后L指针继续右移 别忘了这里也要记录指针
str_re.append([nums[i], nums[L], nums[R]])
R_last nums[R]
L_last nums[L]
elif sum 0:#大于0 R指针左移
R_last nums[R]
R - 1
else:#小于0 L指针右移
L_last nums[L]
return str_re
a Solution()
nums [-1,0,1,2,-1,-4]
print a.threeSum(nums)
不多说了 上代码 双指针的题遇到第二道了已经 希望再次遇到能尽快反应过来