【Java】蓝桥杯-日志统计

题目链接

日志统计

代码

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去存数据,它的长度本身就代表了点赞数,好像可以反过来看时间长度是否满足要求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值