这是我的废物写法
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的一些用法吧。