359. Logger Rate Limiter

题目链接:https://leetcode.com/problems...

和Design Hit Counter基本一样,都可以用hashmap,但是timestamp大了之后会有很多无效的时间保存在hashmap里面,要remove的话,可能需要遍历hashmap或者用list辅助,时间复杂度超过O(1),所以用一个rotate array来做,每次根据新的timestamp改变array。

public class Logger {
    Set<String>[] record;
    int[] times;
    public Logger() {
        record = new Set[10];
        for(int i = 0; i < record.length; i++) record[i] = new HashSet();
        times = new int[10];
        Arrays.fill(times, -10);
    }
    
    /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
        If this method returns false, the message will not be printed.
        The timestamp is in seconds granularity. */
    public boolean shouldPrintMessage(int timestamp, String message) {
        for(int i = 0; i < times.length; i++) {
            if(timestamp - times[i] < 10 && record[i].contains(message)) {
                return false;
            }
        }
        int index = timestamp % 10;
        if(timestamp - times[index] >= 10) {
            // rotate
            times[index] = timestamp;
            record[index] = new HashSet();
        }
        record[index].add(message);
        return true;
    }
}

362. Design Hit Counter

题目链接:https://leetcode.com/problems...

public class HitCounter {

    /** Initialize your data structure here. */
    int[] times;
    int[] hits;
    public HitCounter() {
        times = new int[300];
        hits = new int[300];
    }
    
    public void hit(int timestamp) {
        if(times[timestamp%300] != timestamp) {
            times[timestamp%300] = timestamp;
            hits[timestamp%300] = 1;
        }
        else hits[timestamp%300]++;
    }
    
    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    public int getHits(int timestamp) {
        int count = 0;
        for(int i = 0; i < 300; i++) {
            if(timestamp - times[i] < 300) {
                count += hits[i];
            }
        }
        return count;
    }
}

lulouch13
13 声望6 粉丝