注意点:
- hash方式的利用
- 预先对数组进行排序
- 如何对结果进行去重
源码如下:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
rec_set = set()
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]: #去重1
continue
cur_sum = 0 - nums[i]
cur_hash = {}
for j in range(i+1, len(nums)):
if nums[j] in cur_hash:
if len(res)>0 and nums[j] == res[-1][2] and nums[i]==res[-1][0]: #去重2
continue
res.append([
nums[i],
cur_hash[nums[j]],
nums[j]
])
else:
cur_hash[cur_sum - nums[j]] = nums[j]
return res
网友评论