Problem
Algorithmic thinking
讨论解决方案 https://discuss.leetcode.com/topic/75883/python-solution-with-detailed-explanation
3Sum https://leetcode.com/problems/3sum/
基于排序的算法
- a + b = -c。3SUM减少到2SUM问题。
处理2SUM中的重复项
- 假设索引s和e正在排序数组中形成解决方案。现在给nums [s],有一个独特的nums [e],这样nums [s] + nums [e] = Target。因此,如果nums [s + 1]与nums [s]相同,那么在范围s + 1到e中搜索将给出一个重复的解决方案。因此,我们必须将s移动到nums [s]!= nums [s-1]以避免重复。
while s<e and nums[s] == nums[s-1]:
s = s+1
处理3SUM中的重复项
- 想象一下,我们在索引i处,我们已经从索引i + 1调用了2SUM问题到数组的末尾。现在一旦2SUM终止,我们将有一个包含nums [i]的所有三元组的列表。为了避免重复,我们必须跳过所有nums [i],其中nums [i] == nums [i-1]。
if i > 0 and nums[i] == nums[i-1]:
continue
Python解法:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
N, result = len(nums), []
for i in range(N):
if i > 0 and nums[i] == nums[i-1]:
continue
target = nums[i]*-1
s,e = i+1, N-1
while s<e:
if nums[s]+nums[e] == target:
result.append([nums[i], nums[s], nums[e]])
s = s+1
while s<e and nums[s] == nums[s-1]:
s = s+1
elif nums[s] + nums[e] < target:
s = s+1
else:
e = e-1
return result
相关文档:
https://leetcode.com/problems/3sum/discuss/7498/Python-solution-with-detailed-explanation
Python3 other solution
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
3Sum 三数之和
eg: -1+0+1=0
"""
class Solution:
def threeSum(self, nums):
"""
@param nums: list[int]
@return: List[List[int]]
"""
d = {}
for val in nums:
d[val] = d.get(val, 0) + 1
pos = [x for x in d if x > 0]
neg = [x for x in d if x < 0]
res = []
if d.get(0, 0) > 2:
res.append([0, 0, 0])
for x in pos:
for y in neg:
s = -(x + y)
if s in d:
if s == x and d[x] > 1:
res.append([x, x, y])
elif s == y and d[y] > 1:
res.append([x, y, y])
elif y < s < x:
res.append([x, y, s])
return res
if __name__ == '__main__':
sl_1 = [-1, 0, 1, -2, 2, -3, 3]
result = Solution().threeSum(sl_1)
print(result)