c语言sscanf函数的用法是什么
325
2022-08-27
[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 ith 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 <= 1050 <= 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 defaultdictclass 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
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~