|
| 1 | +// Source : https://leetcode.com/problems/count-good-meals/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-30 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * A good meal is a meal that contains exactly two different food items with a sum of deliciousness |
| 8 | + * equal to a power of two. |
| 9 | + * |
| 10 | + * You can pick any two different foods to make a good meal. |
| 11 | + * |
| 12 | + * Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i^ |
| 13 | + * th item of food, return the number of different good meals you can make from this list |
| 14 | + * modulo 10^9 + 7. |
| 15 | + * |
| 16 | + * Note that items with different indices are considered different even if they have the same |
| 17 | + * deliciousness value. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: deliciousness = [1,3,5,7,9] |
| 22 | + * Output: 4 |
| 23 | + * Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). |
| 24 | + * Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. |
| 25 | + * |
| 26 | + * Example 2: |
| 27 | + * |
| 28 | + * Input: deliciousness = [1,1,1,3,3,3,7] |
| 29 | + * Output: 15 |
| 30 | + * Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. |
| 31 | + * |
| 32 | + * Constraints: |
| 33 | + * |
| 34 | + * 1 <= deliciousness.length <= 10^5 |
| 35 | + * 0 <= deliciousness[i] <= 2^20 |
| 36 | + ******************************************************************************************************/ |
| 37 | + |
| 38 | +class Solution { |
| 39 | +public: |
| 40 | + int countPairs(vector<int>& deliciousness) { |
| 41 | + const int MAX_EXP = 22; |
| 42 | + int pow2[MAX_EXP]; |
| 43 | + for (int i=0; i<MAX_EXP; i++){ |
| 44 | + pow2[i] = 1 << i; |
| 45 | + //cout << pow2[i] << ", "; |
| 46 | + } |
| 47 | + |
| 48 | + unordered_map<int, int> stat; |
| 49 | + int big = 0; |
| 50 | + for(auto& d: deliciousness){ |
| 51 | + stat[d]++; |
| 52 | + |
| 53 | + } |
| 54 | + |
| 55 | + long m = 0; |
| 56 | + for(auto& d: deliciousness){ |
| 57 | + for(int i=MAX_EXP-1; i>=0 && pow2[i] >= d; i--){ |
| 58 | + int x = pow2[i] - d; |
| 59 | + if ( stat.find(x) != stat.end() ){ |
| 60 | + m += (x==d) ? stat[x]-1 : stat[x]; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // remove the duplication - m/2, |
| 66 | + // because both [1,3] and [3,1] are counted. |
| 67 | + return (m/2) % 1000000007; |
| 68 | + } |
| 69 | +}; |
0 commit comments