Given an integer array hours representing times in hours , return an integer denoting the number of pairs i, j where i < j and hours[i] + hours[j] forms a complete day.
A complete day is defined as a time duration that is an exactmultiple of 24 hours.
For example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
If (hours[i] + hours[j]) is a multiple of 24, then (hours[i] % 24 + hours[j] % 24) % 24 == 0. We can count the frequency of each remainder and for each hour, count how many previous hours can pair with it to form a complete day. This is similar to the I version, but needs to be efficient for large n.
classSolution {
public:longlong countPairs(vector<int>& hours) {
vector<longlong> cnt(24, 0);
longlong ans =0;
for (int h : hours) {
int r = h %24;
int comp = (24- r) %24;
ans += cnt[comp];
cnt[r]++;
}
return ans;
}
};
classSolution {
publiclongcountPairs(int[] hours) {
long[] cnt =newlong[24];
long ans = 0;
for (int h : hours) {
int r = h % 24;
int comp = (24 - r) % 24;
ans += cnt[comp];
cnt[r]++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funcountPairs(hours: IntArray): Long {
val cnt = LongArray(24)
var ans = 0Lfor (h in hours) {
val r = h % 24val comp = (24 - r) % 24 ans += cnt[comp]
cnt[r]++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcountPairs(self, hours: list[int]) -> int:
cnt = [0] *24 ans =0for h in hours:
r = h %24 comp = (24- r) %24 ans += cnt[comp]
cnt[r] +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfncount_pairs(hours: Vec<i32>) -> i64 {
letmut cnt = [0i64; 24];
letmut ans =0i64;
for h in hours {
let r = (h %24) asusize;
let comp = (24- r) %24;
ans += cnt[comp];
cnt[r] +=1;
}
ans
}
}