publicclassSolution { publicintCountPairs(int[] deliciousness) { constint MOD = 1000000007; int maxVal = 0; foreach (int val in deliciousness) { maxVal = Math.Max(maxVal, val); } int maxSum = maxVal * 2; int pairs = 0; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int n = deliciousness.Length; for (int i = 0; i < n; i++) { int val = deliciousness[i]; for (int sum = 1; sum <= maxSum; sum <<= 1) { int count = 0; dictionary.TryGetValue(sum - val, out count); pairs = (pairs + count) % MOD; } if (dictionary.ContainsKey(val)) { dictionary[val]++; } else { dictionary.Add(val, 1); } } return pairs; } }
structHashTable { int key, val; UT_hash_handle hh; };
constint MOD = 1000000007;
intcountPairs(int* deliciousness, int deliciousnessSize) { int maxVal = 0; for (int i = 0; i < deliciousnessSize; i++) { maxVal = fmax(maxVal, deliciousness[i]); } int maxSum = maxVal * 2; int pairs = 0; structHashTable *hashTable =NULL, *tmp; int n = deliciousnessSize; for (int i = 0; i < deliciousnessSize; i++) { int val = deliciousness[i]; for (int sum = 1; sum <= maxSum; sum <<= 1) { int target = sum - val; HASH_FIND_INT(hashTable, &target, tmp); int count = tmp == NULL ? 0 : tmp->val; pairs = (pairs + count) % MOD; } HASH_FIND_INT(hashTable, &val, tmp); if (tmp == NULL) { tmp = malloc(sizeof(struct HashTable)); tmp->key = val, tmp->val = 1; HASH_ADD_INT(hashTable, key, tmp); } else { tmp->val++; } } return pairs; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funccountPairs(deliciousness []int) (ans int) { maxVal := deliciousness[0] for _, val := range deliciousness[1:] { if val > maxVal { maxVal = val } } maxSum := maxVal * 2 cnt := map[int]int{} for _, val := range deliciousness { for sum := 1; sum <= maxSum; sum <<= 1 { ans += cnt[sum-val] } cnt[val]++ } return ans % (1e9 + 7) }
复杂度分析
时间复杂度:O(n \log C),其中 n 是数组 deliciousness 的长度,C 是数组 deliciousness 中的元素值上限,这道题中 C=2^{20。需要遍历数组 deliciousness 一次,对于其中的每个元素,需要 O(\log C) 的时间计算包含该元素的大餐数量,因此总时间复杂度是 O(n \log C)。
空间复杂度:O(n),其中 n 是数组 deliciousness 的长度。需要创建哈希表,哈希表的大小不超过 n。