From 767c7fdccac05d404e7c1b1463e2b5a7d41c8aee Mon Sep 17 00:00:00 2001 From: tw2665 <55668073+tw2665@users.noreply.github.com> Date: Thu, 20 May 2021 16:26:12 -0400 Subject: [PATCH] add python solution to 0018.4sum --- problems/0018.四数之和.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index ff441bf7..5012c35e 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -165,7 +165,39 @@ class Solution { ``` Python: +```python3 +class Solution(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :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 + + # good thing about using python is you can use set to drop duplicates. + ans = set() + 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. + count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val) + if hashmap[val] > count: + ans.add(tuple(sorted([nums[i], nums[j], nums[k], val]))) + else: + continue + return ans + +``` Go: