class Solution:
def threeSum(self, nums):
n = len(nums)
# 升序 下面去重要用到
nums.sort()
res = []
# 找到三数之和等于0,只需要循环n-3次
for i in range(n - 2):
# 去除邻近相同元素
if i > 0 and nums[i] == nums[i - 1]:
continue
# 建立双指针
l = i + 1
r = n - 1
while (l < r):
if (nums[i] + nums[l] + nums[r] < 0):
l = l + 1
elif (nums[i] + nums[l] + nums[r] > 0):
r = r - 1
else:
res.append([nums[i], nums[l], nums[r]])
# 去除邻近相同元素 防止添加的元素相同
while (l < r and nums[l] == nums[l + 1]):
l = l + 1
while (l < r and nums[r] == nums[r - 1]):
r = r - 1
l = l + 1
r = r - 1
return res
res = Solution()
print(res.threeSum([-1, 0, 0, 1, 1, 2, 2, -1, 4]))
三数之和-python
最新推荐文章于 2022-10-28 04:17:45 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)