AcWing 1238. 日志统计
小明维护着一个程序员论坛。现在他收集了一份”点赞”日志,日志共有 N 行。
其中每一行的格式是:
ts id
表示在 ts 时刻编号 id 的帖子收到一个”赞”。
现在小明想统计有哪些帖子曾经是”热帖”。
如果一个帖子曾在任意一个长度为 D 的时间段内收到不少于 K 个赞,小明就认为这个帖子曾是”热帖”。
具体来说,如果存在某个时刻 T 满足该帖在 [T,T+D) 这段时间内(注意是左闭右开区间)收到不少于 K 个赞,该帖就曾是”热帖”。
给定日志,请你帮助小明统计出所有曾是”热帖”的帖子编号。
输入格式
第一行包含三个整数 N,D,K。
以下 N 行每行一条日志,包含两个整数 ts 和 id。
输出格式
按从小到大的顺序输出热帖 id。
每个 id 占一行。
数据范围
1≤K≤N≤105,
0≤ts,id≤105,
1≤D≤10000
输入样例:
7 10 2
0 1
0 10
10 10
10 1
9 1
100 3
100 3
输出样例:
1
3
题意:给出n个日志,每个日志代表某个时间点某个帖子获得一个赞,如果一个帖子在d时间段内获得不少于k个赞则为热门,判断有多少热门贴并输出
常规做法循环时间段,循环id计数会超时,这里要是用到双指针方法
首先记录日志并按照时间升序排序,接着定义指针 i 在前即时间段右侧,指针 j 在后即时间段左侧,每次check前指针 i 的id贴是否热门
这里我原先思路是每次check后指针 j 来判断热门,但按照时间段的向后移动,j指针的停止位置是最后日志时间 log[n].t - d ,这个时间段的点赞数会被略掉造成错误,而前指针 i 是从0一直遍历至最后,因此不会有遗漏
因为每次check的是前指针 i ,因此在循环中先计数一个log[i].id,随后判断双指针间的时间段是否超过范围,如果超过则将后指针前移直至符合范围,每次前移要将被略去的日志id计数减一,当符合范围后则check前指针 i 所指的贴id是否为热门即可
代码如下
import java.io.*;
import java.util.*;
public class Main {
static Scanner tab = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int N = 100010;
static PII log[]=new PII[N];//记录日志信息
static boolean st[]=new boolean[N];//判断热门
static int cnt[]=new int [N];//点赞计数
static class PII implements Comparable<PII>{
int t;
int id;
public PII(int t, int id) {
super();
this.t = t;
this.id = id;
}
@Override
public int compareTo(PII o) {
// TODO Auto-generated method stub
return Integer.compare(t, o.t);
}
}
public static void main(String[] args) throws IOException {
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int d=Integer.parseInt(s1[1]);
int k=Integer.parseInt(s1[2]);
for(int i=0;i<n;i++) {
String s2[]=br.readLine().split(" ");
int t=Integer.parseInt(s2[0]);
int id=Integer.parseInt(s2[1]);
log[i]=new PII(t, id);
}
Arrays.sort(log,0,n);
for(int i=0,j=0;i<n;i++) {
int id=log[i].id;
cnt[id]++;
//超出范围则后指针前移至范围内
while(log[i].t-log[j].t>=d) {
cnt[log[j].id]--;//减去计数
j++;
}
if(cnt[id]>=k)//判断前指针热门
st[id]=true;
}
for(int i=0;i<N;i++) {
if(st[i])
System.out.println(i);
}
}
}