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
|
||||
:rtype: List[List[int]]
|
||||
"""
|
||||
# use a dict to store value:showtimes
|
||||
hashmap = dict()
|
||||
for n in nums:
|
||||
if n in hashmap:
|
||||
hashmap[n] += 1
|
||||
else:
|
||||
hashmap[n] = 1
|
||||
# 创建一个字典来存储输入列表中每个数字的频率
|
||||
freq = {}
|
||||
for num in nums:
|
||||
freq[num] = freq.get(num, 0) + 1
|
||||
|
||||
# good thing about using python is you can use set to drop duplicates.
|
||||
# 创建一个集合来存储最终答案,并遍历4个数字的所有唯一组合
|
||||
ans = set()
|
||||
# ans = [] # save results by list()
|
||||
for i in range(len(nums)):
|
||||
for j in range(i + 1, len(nums)):
|
||||
for k in range(j + 1, len(nums)):
|
||||
val = target - (nums[i] + nums[j] + nums[k])
|
||||
if val in hashmap:
|
||||
# make sure no duplicates.
|
||||
if val in freq:
|
||||
# 确保没有重复
|
||||
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
|
||||
if hashmap[val] > count:
|
||||
ans_tmp = 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
|
||||
if freq[val] > count:
|
||||
ans.add(tuple(sorted([nums[i], nums[j], nums[k], val])))
|
||||
|
||||
return [list(x) for x in ans]
|
||||
|
||||
```
|
||||
|
||||
Go:
|
||||
|
Reference in New Issue
Block a user