Skip to content

Commit

Permalink
add python solution to 0018.4sum
Browse files Browse the repository at this point in the history
  • Loading branch information
tw2665 authored May 20, 2021
1 parent 942bd65 commit 767c7fd
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion problems/0018.四数之和.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down

0 comments on commit 767c7fd

Please sign in to comment.