mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Merge pull request #217 from tw2665/patch-3
add python solution to 0018.4sum
This commit is contained in:
@ -165,7 +165,39 @@ class Solution {
|
||||
```
|
||||
|
||||
Python:
|
||||
```python
|
||||
|
||||
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:
|
||||
|
||||
|
Reference in New Issue
Block a user