LeetCode 3184: Count Pairs That Form a Complete Day I (Remainder Counting)
LeetCode 3184Source: https://leetcode.com/problems/count-pairs-that-form-a-complete-day-i/
English
Two durations form one full day when their sum is divisible by 24. For each hour value h, compute r = h % 24 and count how many earlier values have remainder (24-r)%24.
class Solution {
public int countCompleteDayPairs(int[] hours) {
int[] cnt = new int[24];
int ans = 0;
for (int h : hours) {
int r = h % 24;
int need = (24 - r) % 24;
ans += cnt[need];
cnt[r]++;
}
return ans;
}
}func countCompleteDayPairs(hours []int) int {
cnt := make([]int, 24)
ans := 0
for _, h := range hours {
r := h % 24
need := (24 - r) % 24
ans += cnt[need]
cnt[r]++
}
return ans
}class Solution {
public:
int countCompleteDayPairs(vector<int>& hours) {
vector<int> cnt(24);
int ans = 0;
for (int h : hours) {
int r = h % 24;
int need = (24 - r) % 24;
ans += cnt[need];
cnt[r]++;
}
return ans;
}
};class Solution:
def countCompleteDayPairs(self, hours: list[int]) -> int:
cnt = [0] * 24
ans = 0
for h in hours:
r = h % 24
need = (24 - r) % 24
ans += cnt[need]
cnt[r] += 1
return ansfunction countCompleteDayPairs(hours) {
const cnt = Array(24).fill(0);
let ans = 0;
for (const h of hours) {
const r = h % 24;
const need = (24 - r) % 24;
ans += cnt[need];
cnt[r]++;
}
return ans;
}中文
两个时长之和能被 24 整除,就能组成完整的一天。遍历每个 h,令 r=h%24,需要匹配的余数是 (24-r)%24,用计数数组累计即可,时间复杂度 O(n)。
class Solution {
public int countCompleteDayPairs(int[] hours) {
int[] cnt = new int[24];
int ans = 0;
for (int h : hours) {
int r = h % 24;
int need = (24 - r) % 24;
ans += cnt[need];
cnt[r]++;
}
return ans;
}
}func countCompleteDayPairs(hours []int) int {
cnt := make([]int, 24)
ans := 0
for _, h := range hours {
r := h % 24
need := (24 - r) % 24
ans += cnt[need]
cnt[r]++
}
return ans
}class Solution {
public:
int countCompleteDayPairs(vector<int>& hours) {
vector<int> cnt(24);
int ans = 0;
for (int h : hours) {
int r = h % 24;
int need = (24 - r) % 24;
ans += cnt[need];
cnt[r]++;
}
return ans;
}
};class Solution:
def countCompleteDayPairs(self, hours: list[int]) -> int:
cnt = [0] * 24
ans = 0
for h in hours:
r = h % 24
need = (24 - r) % 24
ans += cnt[need]
cnt[r] += 1
return ansfunction countCompleteDayPairs(hours) {
const cnt = Array(24).fill(0);
let ans = 0;
for (const h of hours) {
const r = h % 24;
const need = (24 - r) % 24;
ans += cnt[need];
cnt[r]++;
}
return ans;
}
Comments