mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Update 0018.四数之和.md
This commit is contained in:
@ -252,36 +252,25 @@ class Solution(object):
|
|||||||
:type target: int
|
:type target: int
|
||||||
:rtype: List[List[int]]
|
:rtype: List[List[int]]
|
||||||
"""
|
"""
|
||||||
# use a dict to store value:showtimes
|
# 创建一个字典来存储输入列表中每个数字的频率
|
||||||
hashmap = dict()
|
freq = {}
|
||||||
for n in nums:
|
for num in nums:
|
||||||
if n in hashmap:
|
freq[num] = freq.get(num, 0) + 1
|
||||||
hashmap[n] += 1
|
|
||||||
else:
|
|
||||||
hashmap[n] = 1
|
|
||||||
|
|
||||||
# good thing about using python is you can use set to drop duplicates.
|
# 创建一个集合来存储最终答案,并遍历4个数字的所有唯一组合
|
||||||
ans = set()
|
ans = set()
|
||||||
# ans = [] # save results by list()
|
|
||||||
for i in range(len(nums)):
|
for i in range(len(nums)):
|
||||||
for j in range(i + 1, len(nums)):
|
for j in range(i + 1, len(nums)):
|
||||||
for k in range(j + 1, len(nums)):
|
for k in range(j + 1, len(nums)):
|
||||||
val = target - (nums[i] + nums[j] + nums[k])
|
val = target - (nums[i] + nums[j] + nums[k])
|
||||||
if val in hashmap:
|
if val in freq:
|
||||||
# make sure no duplicates.
|
# 确保没有重复
|
||||||
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
|
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
|
||||||
if hashmap[val] > count:
|
if freq[val] > count:
|
||||||
ans_tmp = tuple(sorted([nums[i], nums[j], nums[k], val]))
|
ans.add(tuple(sorted([nums[i], nums[j], nums[k], val])))
|
||||||
ans.add(ans_tmp)
|
|
||||||
# Avoiding duplication in list manner but it cause time complexity increases
|
|
||||||
# if ans_tmp not in ans:
|
|
||||||
# ans.append(ans_tmp)
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
return list(ans)
|
|
||||||
# if used list() to save results, just
|
|
||||||
# return ans
|
|
||||||
|
|
||||||
|
return [list(x) for x in ans]
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
Reference in New Issue
Block a user