1. 程式人生 > 其它 >最近請求次數(TreeMap應用)

最近請求次數(TreeMap應用)

這是我的廢物寫法

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的一些用法吧。