数据结构算法操作试题(C++/Python)——四数之和

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——四数之和,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/4sum/

2. 解答

解法1: 排序,双指针夹逼

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

解法2: 排序 + Hash

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 链接 评论区~