题目
https://leetcode.com/problems/3sum/
15. 3Sum
Medium
3647399FavoriteShare
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
代码:
错误示例:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = list()
sort_list = sorted(nums)
# print(sort_list)
for i, a in enumerate(sort_list):
for j, b in enumerate(sort_list[i+1:]):
c = (a + b)
if -c in sort_list[i+j+2:]: # 首先要去有序list里面找一个数,可以用hashmap或者二分法查找的方式
lists = sorted([a,b,-c])
if lists not in res: # 如果后期res越来越大,这个in也是逐个比对的,时间消耗很多,相当于一个for循环
res.append([a,b,-c])
return sorted(res)
正确示例:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = list()
sort_list = sorted(nums)
d = {}
# if len(sort_list) == 0:
# return res
for num in sort_list:
d[num] = d.get(num, 0) + 1
a_set = set()
for i, a in enumerate(sort_list):
if a in a_set:
continue
if a>0 :
return res
b_set = set()
for j, b in enumerate(sort_list[i+1:]):
if b in b_set:
continue
if a+2*b > 0:
break
c = (a + b)
if (-c>b and d.get(-c) is not None) or (-c==b and b>a and d.get(-c, 0)>=2) or (-c==b and b==a and d.get(-c,0) >= 3):
res.append([a, b, -c])
b_set.add(b)
a_set.add(a)
return res
总结:
1. 排序
2. 利用条件判断尽快终止循环,如: if a+2*b > 0; if a>0
3. 利用字典减少搜索时间
4. 设置set存放搜索过的数字,以便下次出现重复数字,不再尝试