首页 > 其他 > 详细

最近请求次数(TreeMap应用)

时间:2021-08-30 07:58:17      阅读:9      评论:0      收藏:0      [点我收藏+]

技术分享图片

这是我的废物写法

class RecentCounter {
    Deque<Integer> sta;
    public RecentCounter() {
        this.sta = new LinkedList<>(); 
    }
    
    public int ping(int t) {
        int res = 1;
        Deque<Integer> test = new LinkedList<>();
        while(!sta.isEmpty() && sta.peekLast() >= t-3000){
            test.addLast(sta.pollLast());
            res++;
        }
        while(!test.isEmpty()){
            sta.addLast(test.pollLast());
        }
        sta.addLast(t);
        return res;
    }
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */

这是应用TreeMap

java中的TreeMap是一类有序集合,能够快速返回一个特定大小的值,例如下面用到的ceilingKey,就是返回TreeMap中第一个大于等于t-3000的值,类似的函数还有floor等,用起来很方便

class RecentCounter {

    TreeMap<Integer, Integer> tm;
    List<Integer> record;
    
    public RecentCounter() {
        tm = new TreeMap<>();
        record = new ArrayList<>();
    }

    public int ping(int t) {
        tm.put(t, record.size());
        record.add(t);
        Integer target = tm.ceilingKey(t - 3000);
        return record.size() - tm.get(target);
    }
}

之后更新一下TreeMap的一些用法吧。

最近请求次数(TreeMap应用)

原文:https://www.cnblogs.com/Dkfeng/p/15202851.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!