思路
- 排序.
- 固定第一个加数,双指针遍历.
- 三数和为: ret = nums[i] + nums[l] + nums[r]
- 判断是否ret == 0
- 优化: 针对重复数据,和大于0之后的数据,去重。
代码
#!/usr/bin/env python
"""
doc:
"""
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return list()
nums.sort()
ans = list()
visited = set()
for i in range(len(nums)-2):
target = nums[i]
if target > 0:
continue
if target in visited:
continue
visited.add(target)
l = i + 1
r = len(nums) - 1
while l < r:
ret = target + nums[l] + nums[r]
if ret == 0:
ret_list = [target, nums[l], nums[r]]
ans.append(ret_list)
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
r -= 1
while r > l and nums[r] == nums[r+1]:
r -= 1
elif ret > 0:
r -= 1
while r > l and nums[r] == nums[r+1]:
r -= 1
elif ret < 0:
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
return ans
def main():
nums = [0,0,0]
ret = Solution().threeSum(nums)
print(ret)
if __name__ == '__main__':
main()
来源:oschina
链接:https://my.oschina.net/tplinuxhyh/blog/4321632