From c4bc3197502473c5f14be392157bb83ddaa2dbeb Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:39:52 -0500 Subject: [PATCH] =?UTF-8?q?Update=200018.=E5=9B=9B=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 33 +++++++++++---------------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 4fee8358..a4d41d9b 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -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: