【18/M/python】4Sum

题目

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

思路

可以和之前3Sum的思路一样,采用快排,时间复杂度为O(N^3),但是很容易超时,所以这里采用另外一种方法,哈希表用空间换时间,以增加空间复杂度的代价来降低时间复杂度。首先建立一个字典dict,字典的key值为数组中每两个元素的和,每个key对应的value为这两个元素的下标组成的元组,元组不一定是唯一的。
如对于num=[1,2,3,2]来说,dict={3:[(0,1),(0,3)], 4:[(0,2),(1,3)], 5:[(1,2),(2,3)]}。
这样就可以检查target-key这个值在不在dict的key值中,如果target-key在dict中并且下标符合要求,那么就找到了这样的一组解。由于需要去重,这里选用set()类型的数据结构,即无序无重复元素集。最后将每个找出来的解(set()类型)转换成list类型输出即可。

代码

class Solution:
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        numlen,res,adict = len(nums),set(),{}

        # 如果输入数字不够直接返回空列表
        if numlen < 4:
            return []

        # 构建哈希表,如对于num=[1,2,3,2]来说,dict={3:[(0,1),(0,3)], 4:[(0,2),(1,3)], 5:[(1,2),(2,3)]}
        nums.sort()
        for i in range(numlen):
            for j in range(i+1,numlen):
                if nums[i]+nums[j] not in adict:
                    adict[nums[i]+nums[j]] = [(i,j)]
                else:
                    adict[nums[i]+nums[j]].append((i,j))

        for i in range(numlen):
            for j in range(i+1,numlen-2):
                digit = target - nums[i] - nums[j]
                if digit in adict:
                    for item in adict[digit]:
                        if item[0] > j:
                            res.add((nums[i],nums[j],nums[item[0]],nums[item[1]]))
        return [list(k) for k in res]

运行结果

282 / 282 test cases passed.
Status: Accepted
Runtime: 160 ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值