leetcode 三数之和的多种可能

3 篇文章 0 订阅
1 篇文章 0 订阅

给定一个整数数组 A,以及一个整数 target 作为目标值,返回满足 i < j < k 且 A[i] + A[j] + A[k] == target 的元组 i, j, k 的数量。

由于结果会非常大,请返回 结果除以 10^9 + 7 的余数。

示例 1:

输入:A = [1,1,2,2,3,3,4,4,5,5], target = 8
输出:20
解释:
按值枚举(A[i],A[j],A[k]):
(1, 2, 5) 出现 8 次;
(1, 3, 4) 出现 8 次;
(2, 2, 4) 出现 2 次;
(2, 3, 3) 出现 2 次。
示例 2:

输入:A = [1,1,2,2,2,2], target = 5
输出:12
解释:
A[i] = 1,A[j] = A[k] = 2 出现 12 次:
我们从 [1,1] 中选择一个 1,有 2 种情况,
从 [2,2,2,2] 中选出两个 2,有 6 种情况。

提示:

3 <= A.length <= 3000
0 <= A[i] <= 100
0 <= target <= 300

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-with-multiplicity
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分析: 这道题一共有3种情况
把A中元素存在字典dict里
a=b=c dict(a)(dict(a)-1)(dict(a)-2)/6
a=b!=c dict(a)*(dict(a)-1)*dict©/2
a<b<c dict(a)*dict(b)*dict©

用一个Counter就很容易处理啦

from collections import Counter
class Solution(object):
    def threeSumMulti(self, A, target):
        """
        :type A: List[int]
        :type target: int
        :rtype: int
        """
        c=Counter(A)
        res=0
        for i,x in c.items():
            for j,y in c.items():
                k=target-i-j
                if k not in c:
                    continue
                if i==j==k:
                    if c[k]>2:
                        res=(res+(x*(x-1)*(x-2))/6)%(pow(10,9)+7)
                elif i==j!=k:
                    res=(res+x*(x-1)*c[k]/2)%(pow(10,9)+7)
                elif i<j<k:
                    res=(res+x*y*c[k])%(pow(10,9)+7)
        return res

三数之和的另一种思路:题目链接
先把数组排序,确定基准元素后,用双指针 l,r 每次缩小范围,时间复杂度为 O(n*n)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums = sorted(nums)
        for i in range(len(nums)):
            if nums[i] > 0:
                break
            if i > 0 and nums[i] == nums[i-1]:  ### 去重
                continue
            l, r = i+1, len(nums)-1
            while l < r:
                if nums[i] + nums[l] + nums[r] == 0:
                    res.append([nums[i], nums[l], nums[r]])
                    ## 去重, if nums[l] < nums[r], nums[l] 变大,nums[r] 需变小
                    ##if nums[l] == nums[r], 同样
                    while l < r and nums[l] == nums[l+1]: 
                        l += 1
                    while l < r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1
                    r -= 1
                elif nums[i] + nums[l] + nums[r] > 0:
                    r -= 1
                else:
                    l += 1
        return res    

四数之和链接,用一个 map 存两个数组的两两之和。

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        numbers = len(nums1)
        a = collections.defaultdict(int)
        for i in range(numbers):
            for j in range(numbers):
                a[nums3[i]+nums4[j]] += 1
        
        res = 0
        for i in range(numbers):
            for j in range(numbers):
                target = -nums1[i]-nums2[j]
                res += a[target]
        return res
                        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值