数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录
leetcode 链接:https://leetcode-cn.com/problems/4sum/
python:656 ms,10.8 MB
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
res = []
for i in range(len(nums) - 3):
for j in range(i + 1, len(nums) - 2):
tmp_sum = nums[i] + nums[j]
start = j + 1
end = len(nums) -1
while start < end:
if nums[start] + nums[end] + tmp_sum < target:
start += 1
elif nums[start] + nums[end] + tmp_sum > target:
end -= 1
else:
tmp_list = [nums[i], nums[j], nums[start], nums[end]]
if tmp_list not in res: res.append(tmp_list)
start += 1
end -= 1
return res
python:136ms, 15.1MB
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums, result, lookup = sorted(nums), [], collections.defaultdict(list)
for i in xrange(0, len(nums) - 1):
for j in xrange(i + 1, len(nums)):
is_duplicated = False
for [x, y] in lookup[nums[i] + nums[j]]:
if nums[x] == nums[i]:
is_duplicated = True
break
if not is_duplicated:
lookup[nums[i] + nums[j]].append([i, j])
ans = {}
for c in xrange(2, len(nums)):
for d in xrange(c+1, len(nums)):
if target - nums[c] - nums[d] in lookup:
for [a, b] in lookup[target - nums[c] - nums[d]]:
if b < c:
quad = [nums[a], nums[b], nums[c], nums[d]]
quad_hash = " ".join(str(quad))
if quad_hash not in ans:
ans[quad_hash] = True
result.append(quad)
return result
其他方法看 leetcode 链接 评论区~