Skip to content

Latest commit

 

History

History
122 lines (93 loc) · 3.11 KB

File metadata and controls

122 lines (93 loc) · 3.11 KB

中文文档

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

Solutions

Python3

class Solution:
    def countPairs(self, deliciousness: List[int]) -> int:
        mod = 1000000007
        limit = max(deliciousness) * 2
        pairs = 0
        freq = collections.defaultdict(int)
        for d in deliciousness:
            target = 1
            while target <= limit:
                pairs = (pairs + freq[target - d]) % mod
                target = target << 1
            freq[d] += 1
        return pairs

Java

class Solution {

    private static final int MOD = 1000000007;

    public int countPairs(int[] deliciousness) {
        int limit = Arrays.stream(deliciousness).max().getAsInt() * 2;
        int pairs = 0;
        Map<Integer, Integer> freq = new HashMap<>();
        for (int d : deliciousness) {
            for (int sum = 1; sum <= limit; sum <<= 1) {
                int count = freq.getOrDefault(sum - d, 0);
                pairs = (pairs + count) % MOD;
            }
            freq.merge(d, 1, Integer::sum);
        }
        return pairs;
    }
}

Go

const mod int = 1e9 + 7

func countPairs(deliciousness []int) int {
	limit := 0
	for _, d := range deliciousness {
		limit = max(limit, d)
	}
	limit *= 2
	pairs := 0
	freq := make(map[int]int)
	for _, d := range deliciousness {
		for sum := 1; sum <= limit; sum <<= 1 {
			pairs = (pairs + freq[sum-d]) % mod
		}
		freq[d]++
	}
	return pairs
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

...