其他分享
首页 > 其他分享> > <Design> 359 346

<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();
    }
}

标签:map,int,timestamp,sum,346,message,359,size
来源: https://www.cnblogs.com/Afei-1123/p/12056213.html