首页 > 其他 > 详细

<Design> 359 346

时间:2019-12-17 20:09:41      阅读:79      评论:0      收藏:0      [点我收藏+]

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

<Design> 359 346

原文:https://www.cnblogs.com/Afei-1123/p/12056213.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!