1711. 大餐计数 - 力扣(LeetCode) (leetcode-cn.com)
1、由于他们的和为2的幂,且,他们两数之和必然小于2^21,所以他们的和的个数有限,所以可以通过枚举每个数组中的数和另外一个数的和去得到大餐的个数。
用一个数组cnt去记录某个数出现的次数,然后逐个数去判断它对应的另一个数是否出现过(如果出现过那将被记录了出现次数),则将其的出现次数累加到大餐个数中。
下面是按照英雄哪里出来大佬的思路写的,将两个过程合起来。
class Solution {
public:
int countPairs(vector<int>& deliciousness) {
int thesize=deliciousness.size();
const int max=1<<21;
int cnt[max+1]={0};
int ans=0,other;
for(int i=0;i<thesize;++i)
{
for(int j=1;j<=max;j<<=1)
{
other=j-deliciousness[i];
if(other<0) continue;
ans+=cnt[other];
ans%=1000000007;
}
++cnt[deliciousness[i]];
}
return ans;
}
};