[leetcode] 1711. Count Good Meals

Description

A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.

You can pick any two different foods to make a good meal.

Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7.

Note that items with different indices are considered different even if they have the same deliciousness value.

Example 1:

Input: deliciousness = [1,3,5,7,9]
Output: 4
Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).
Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.
Example 2:

Input: deliciousness = [1,1,1,3,3,3,7]
Output: 15
Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.

Constraints:

  • 1 <= deliciousness.length <= 105
  • 0 <= deliciousness[i] <= 220

分析

题目的意思是:给你一个数组,求出其中能够构成2的n次方的对数,我参考了一下别人的思路,很巧妙,首先用字典d来统计遍历过得deliciousness的数字,res来统计符合条件的对数,其中2的n次方最小是0,最大是2的22次方,因此一个一个的遍历是否满足构成条件就行了。核心代码如下

res+=d[2**i-num]

直接在字典里面找出能够构成2的i次方的数进行统计就行了。如果有不懂的,可以参考代码二,在本地调试一下

代码

class Solution:
    def countPairs(self, deliciousness: List[int]) -> int:
        d=defaultdict(int)
        res=0
        for num in deliciousness:
            for i in range(22):
                res+=d[2**i-num]
            d[num]+=1
        return res%(10**9+7)

代码二

from collections import defaultdict
class Solution:
    def countPairs(self, deliciousness) -> int:
        d=defaultdict(int)
        res=0
        for num in deliciousness:
            for i in range(22):
                res+=d[2**i-num]
            d[num]+=1
        print(d)
        return res%(10**9+7)


if __name__=="__main__":
    solution=Solution()
    deliciousness = [1,3,5,7,9]
    res=solution.countPairs(deliciousness)
    print(res)

参考文献

[Python3] frequency table

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值