File tree Expand file tree Collapse file tree 1 file changed +11
-22
lines changed Expand file tree Collapse file tree 1 file changed +11
-22
lines changed Original file line number Diff line number Diff line change @@ -252,36 +252,25 @@ class Solution(object):
252
252
:type target: int
253
253
:rtype: List[List[int]]
254
254
"""
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
262
259
263
- # good thing about using python is you can use set to drop duplicates.
260
+ # 创建一个集合来存储最终答案,并遍历4个数字的所有唯一组合
264
261
ans = set ()
265
- # ans = [] # save results by list()
266
262
for i in range (len (nums)):
267
263
for j in range (i + 1 , len (nums)):
268
264
for k in range (j + 1 , len (nums)):
269
265
val = target - (nums[i] + nums[j] + nums[k])
270
- if val in hashmap :
271
- # make sure no duplicates.
266
+ if val in freq :
267
+ # 确保没有重复
272
268
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])))
284
271
272
+ return [list (x) for x in ans]
273
+
285
274
```
286
275
287
276
Go:
You can’t perform that action at this time.
0 commit comments