小红刷小红书
[题目链接](https://www.nowcoder.com/practice/ce4beb9128124a86a1ea5c2a81ac962c)
思路
本题是一道时间计算模拟题。小红记录了 7 天的刷小红书起止时间,需要计算总共刷了多少分钟。
核心难点:跨越午夜
开始时间一定晚于 17:00,结束时间一定早于 03:00。因此当结束时间的小时数小于开始时间的小时数时,说明跨越了午夜。
统一时间轴
为了方便计算,我们将所有时间统一到同一条时间轴上。具体做法是:
- 把
HH:MM转换为从00:00起的分钟数。
- 如果
(即凌晨 0 点到 3 点之间的时间),说明这个时间实际上是"第二天"的凌晨,给它加上
分钟。
这样,所有时间都映射到 这个区间内,结束时间一定大于等于开始时间,直接做差即可。
样例验证
| 天数 | 开始 | 结束 | 时长(分钟) |
|---|---|---|---|
| 1 | 20:00 | 21:00 | 60 |
| 2 | 20:00 | 23:30 | 210 |
| 3 | 21:00 | 02:00(次日) | 300 |
| 4 | 00:12(次日) | 00:30(次日) | 18 |
| 5 | 18:30 | 19:00 | 30 |
| 6 | 23:00 | 23:05 | 5 |
| 7 | 18:00 | 01:00(次日) | 420 |
总计 。
代码
#include <bits/stdc++.h>
using namespace std;
int main(){
int ans = 0;
for(int i = 0; i < 7; i++){
int h1, m1, h2, m2;
scanf("%d:%d", &h1, &m1);
scanf("%d:%d", &h2, &m2);
int t1 = h1 * 60 + m1;
int t2 = h2 * 60 + m2;
if(h1 < 17) t1 += 24 * 60;
if(h2 < 17) t2 += 24 * 60;
ans += t2 - t1;
}
printf("%d\n", ans);
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int ans = 0;
for (int i = 0; i < 7; i++) {
String[] s1 = sc.next().split(":");
int h1 = Integer.parseInt(s1[0]), m1 = Integer.parseInt(s1[1]);
String[] s2 = sc.next().split(":");
int h2 = Integer.parseInt(s2[0]), m2 = Integer.parseInt(s2[1]);
int t1 = h1 * 60 + m1;
int t2 = h2 * 60 + m2;
if (h1 < 17) t1 += 24 * 60;
if (h2 < 17) t2 += 24 * 60;
ans += t2 - t1;
}
System.out.println(ans);
}
}
ans = 0
for _ in range(7):
h1, m1 = map(int, input().split(':'))
h2, m2 = map(int, input().split(':'))
t1 = h1 * 60 + m1
t2 = h2 * 60 + m2
if h1 < 17:
t1 += 24 * 60
if h2 < 17:
t2 += 24 * 60
ans += t2 - t1
print(ans)
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => {
lines.push(line.trim());
if (lines.length === 14) {
let ans = 0;
for (let i = 0; i < 14; i += 2) {
let [h1, m1] = lines[i].split(':').map(Number);
let [h2, m2] = lines[i + 1].split(':').map(Number);
let t1 = h1 * 60 + m1;
let t2 = h2 * 60 + m2;
if (h1 < 17) t1 += 24 * 60;
if (h2 < 17) t2 += 24 * 60;
ans += t2 - t1;
}
console.log(ans);
rl.close();
}
});
复杂度分析
- 时间复杂度:
,固定循环 7 次,每次进行常数次运算。
- 空间复杂度:
,只使用了若干变量。

京公网安备 11010502036488号