题目链接
代码
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 在此输入您的代码...
int N = scan.nextInt();// N行
int D = scan.nextInt();// 长度为D的时间段
int K = scan.nextInt();// 最低赞数
HashMap<Integer, List<Integer>> idAndTimeMap = new HashMap<>();
for (int i = 0; i < N; i++) {
int ts = scan.nextInt();// 时刻
int id = scan.nextInt();// 帖子号
idAndTimeMap.computeIfAbsent(id, k -> new ArrayList<>()).add(ts);
}
scan.close();
// 用来存储结果
List<Integer> resList = new ArrayList<>();
// 轮流判断每个帖子是不是热帖
for (Map.Entry<Integer, List<Integer>> entry : idAndTimeMap.entrySet()) {
Integer curId = entry.getKey();
List<Integer> curTimeList = entry.getValue();
Collections.sort(curTimeList);
// 一个时间点记录本身就代表了一个赞,可以固定长度K,看首尾的差,是否满足小于D
if (curTimeList.size() < K) {
// 总长度都小于K 说明总赞数就小于K
continue;
} else {
int idxFront = 0;
int idxEnd = K - 1;
while (idxEnd <= curTimeList.size() - 1) {
if (curTimeList.get(idxEnd) - curTimeList.get(idxFront) < D) {
resList.add(curId);
break;
}else{
idxFront++;
idxEnd++;
}
}
}
}
// 打印最终结果
Collections.sort(resList);
for (int id : resList) {
System.out.println(id);
}
}
}
备忘
1、Map接口提供computeIfAbsent方法,检查给定的键是否存在,如果存在则返回其对应的值,如果不存在则使用给定的逻辑初始化并添加该键值对。idAndTimeMap.computeIfAbsent(id, k -> new ArrayList<>()).add(ts);
2、一开始想的是固定时间长度算点赞数,后来发现用List去存数据,它的长度本身就代表了点赞数,好像可以反过来看时间长度是否满足要求。
1606

被折叠的 条评论
为什么被折叠?



