<Design> 359 346

359. Logger Rate Limiter

用map搭建。

class Logger {
    HashMap<String, Integer> map;
    /** Initialize your data structure here. */
    public Logger() {
        map = new HashMap<>();  
    }
    
    /** 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) {
        if(!map.containsKey(message) || timestamp - map.get(message) >= 10){
            map.put(message, timestamp);
            return true;
        }
        return false;
    }
}

346. Moving Average from Data Stream

class MovingAverage {
    private Queue<Integer> q = new LinkedList<>();
    private int size;
    double sum;

    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.size = size;
        sum = 0;
    }
    
    public double next(int val) {
        if(q.size() >= size){
            sum -= q.poll();
        }
        q.offer(val);
        sum += val;
        return sum / q.size();
    }
}

猜你喜欢

转载自www.cnblogs.com/Afei-1123/p/12056213.html