Skip to content

Commit c4bc319

Browse files
Update 0018.四数之和.md
1 parent dde92b1 commit c4bc319

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

problems/0018.四数之和.md

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -252,36 +252,25 @@ class Solution(object):
252252
:type target: int
253253
:rtype: List[List[int]]
254254
"""
255-
# use a dict to store value:showtimes
256-
hashmap = dict()
257-
for n in nums:
258-
if n in hashmap:
259-
hashmap[n] += 1
260-
else:
261-
hashmap[n] = 1
255+
# 创建一个字典来存储输入列表中每个数字的频率
256+
freq = {}
257+
for num in nums:
258+
freq[num] = freq.get(num, 0) + 1
262259

263-
# good thing about using python is you can use set to drop duplicates.
260+
# 创建一个集合来存储最终答案,并遍历4个数字的所有唯一组合
264261
ans = set()
265-
# ans = [] # save results by list()
266262
for i in range(len(nums)):
267263
for j in range(i + 1, len(nums)):
268264
for k in range(j + 1, len(nums)):
269265
val = target - (nums[i] + nums[j] + nums[k])
270-
if val in hashmap:
271-
# make sure no duplicates.
266+
if val in freq:
267+
# 确保没有重复
272268
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
273-
if hashmap[val] > count:
274-
ans_tmp = tuple(sorted([nums[i], nums[j], nums[k], val]))
275-
ans.add(ans_tmp)
276-
# Avoiding duplication in list manner but it cause time complexity increases
277-
# if ans_tmp not in ans:
278-
# ans.append(ans_tmp)
279-
else:
280-
continue
281-
return list(ans)
282-
# if used list() to save results, just
283-
# return ans
269+
if freq[val] > count:
270+
ans.add(tuple(sorted([nums[i], nums[j], nums[k], val])))
284271

272+
return [list(x) for x in ans]
273+
285274
```
286275

287276
Go:

0 commit comments

Comments
 (0)