3184. 构成整天的下标对数目 I
题目描述
给你一个整数数组 hours
,表示以 小时 为单位的时间,返回一个整数,表示满足 i < j
且 hours[i] + hours[j]
构成 整天 的下标对 i
, j
的数目。
整天 定义为时间持续时间是 24 小时的 整数倍 。
例如,1 天是 24 小时,2 天是 48 小时,3 天是 72 小时,以此类推。
示例 1:
输入: hours = [12,12,30,24,24]
输出: 2
解释:
构成整天的下标对分别是 (0, 1)
和 (3, 4)
。
示例 2:
输入: hours = [72,48,24,3]
输出: 3
解释:
构成整天的下标对分别是 (0, 1)
、(0, 2)
和 (1, 2)
。
提示:
1 <= hours.length <= 100
1 <= hours[i] <= 109
解法
方法一:计数
我们可以用一个哈希表或者一个长度为 $24$ 的数组 $\textit{cnt}$ 来记录每个小时数模 $24$ 的出现次数。
遍历数组 $\textit{hours}$,对于每个小时数 $x$,我们可以得出与 $x$ 相加为 $24$ 的倍数,且模 $24$ 之后的数为 $(24 - x \bmod 24) \bmod 24$。累加这个数在哈希表或者数组中的出现次数即可。然后我们将 $x$ 的模 $24$ 的出现次数加一。
遍历完数组 $\textit{hours}$ 后,我们就可以得到满足题意的下标对数目。
时间复杂度 $O(n)$,其中 $n$ 为数组 $\textit{hours}$ 的长度。空间复杂度 $O(C)$,其中 $C=24$。
Python3
class Solution:
def countCompleteDayPairs(self, hours: List[int]) -> int:
cnt = Counter()
ans = 0
for x in hours:
ans += cnt[(24 - (x % 24)) % 24]
cnt[x % 24] += 1
return ans
Java
class Solution {
public int countCompleteDayPairs(int[] hours) {
int[] cnt = new int[24];
int ans = 0;
for (int x : hours) {
ans += cnt[(24 - x % 24) % 24];
++cnt[x % 24];
}
return ans;
}
}
C++
class Solution {
public:
int countCompleteDayPairs(vector<int>& hours) {
int cnt[24]{};
int ans = 0;
for (int x : hours) {
ans += cnt[(24 - x % 24) % 24];
++cnt[x % 24];
}
return ans;
}
};
Go
func countCompleteDayPairs(hours []int) (ans int) {
cnt := [24]int{}
for _, x := range hours {
ans += cnt[(24-x%24)%24]
cnt[x%24]++
}
return
}
TypeScript
function countCompleteDayPairs(hours: number[]): number {
const cnt: number[] = Array(24).fill(0);
let ans: number = 0;
for (const x of hours) {
ans += cnt[(24 - (x % 24)) % 24];
++cnt[x % 24];
}
return ans;
}