蓝桥杯试题 历届真题 日志统计【第八届】【java省赛】

该博客介绍了如何处理一个程序员论坛的日志数据,以找出那些在特定时间段内获得点赞数达到一定数量的“热帖”。通过排序日志条目并使用哈希映射来统计每个帖子在不同时间段内的点赞数,实现了“热帖”的识别。这种方法利用了尺取法优化了时间复杂度,保证了在限制内存和CPU消耗的条件下找到所有热帖的ID。
摘要由CSDN通过智能技术生成

小明维护着一个程序员论坛。现在他收集了一份"点赞"日志,日志共有N行。其中每一行的格式是:

ts id

表示在ts时刻编号id的帖子收到一个"赞"。

现在小明想统计有哪些帖子曾经是"热帖"。如果一个帖子曾在任意一个长度为D的时间段内收到不少于K个赞,小明就认为这个帖子曾是"热帖"。

具体来说,如果存在某个时刻T满足该帖在[T, T+D)这段时间内(注意是左闭右开区间)收到不少于K个赞,该帖就曾是"热帖"。

给定日志,请你帮助小明统计出所有曾是"热帖"的帖子编号。

【输入格式】
第一行包含三个整数N、D和K。
以下N行每行一条日志,包含两个整数ts和id。

对于50%的数据,1 <= K <= N <= 1000
对于100%的数据,1 <= K <= N <= 100000 0 <= ts <= 100000 0 <= id <= 100000

【输出格式】
按从小到大的顺序输出热帖id。每个id一行。

【输入样例】
7 10 2
0 1
0 10
10 10
10 1
9 1
100 3
100 3

【输出样例】
1
3

资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms

请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
 

import org.apache.hadoop.shaded.com.google.common.collect.ForwardingSet;

import java.util.*;

public class Main {
    static class Tsid{
        int ts;
        int id;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int D = scanner.nextInt();
        int K = scanner.nextInt();

        Tsid[] tsids = new Tsid[N];

        for (int i = 0; i < N; i++) {
            Tsid tsid = new Tsid();
            tsid.ts = scanner.nextInt();
            tsid.id = scanner.nextInt();
            tsids[i] = tsid;
        }
        //将ts排序,按照时间段查找
        Arrays.sort(tsids, new Comparator<Tsid>() {
            public int compare(Tsid o1, Tsid o2) {
                return o1.ts - o2.ts;       //按照ts升序排列
            }
        });
        //给id计数,k为ts,v为id
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        //存储各个id号,最终结果
        Set<Integer> set = new TreeSet<Integer>();
        //尺取法
        int j = 0;  //哨兵
        for (int i = 0; i < N; i++) {
            while(j < N && tsids[j].ts - tsids[i].ts < D){
                int id = tsids[i].id;
                Integer count = map.get(id);
                if(count != null){
                    map.put(id,count + 1);    //有id,value + 1
                }else{
                    map.put(id,1);      //没有id,添加进去
                }
                if(map.get(id) >= K){
                    set.add(id);
                }
                j++;
            }
            //将上一个i对应的id的计数 - 1
            Integer integer = map.get(tsids[i].id);
            if(integer != null){
                map.put(tsids[i].id,integer - 1);
            }
        }
        for(int i : set){
            System.out.println(i);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OneTenTwo76

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值