• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

Queue method:

 1 public class MovingAverage {
 2     Queue<Integer> queue;
 3     int capacity;
 4     int sum;
 5 
 6     /** Initialize your data structure here. */
 7     public MovingAverage(int size) {
 8         queue = new LinkedList<Integer>();
 9         capacity = size;
10         sum = 0;
11     }
12     
13     public double next(int val) {
14         if (queue.size() == capacity) {
15             sum -= queue.poll();
16         }
17         sum += val;
18         queue.offer(val);
19         return (double)sum/queue.size();
20     }
21 }
22 
23 /**
24  * Your MovingAverage object will be instantiated and called as such:
25  * MovingAverage obj = new MovingAverage(size);
26  * double param_1 = obj.next(val);
27  */

Array method: 非常聪明

 1 public class MovingAverage {
 2     private int [] window;
 3     private int n, insert;
 4     private long sum;
 5     
 6     /** Initialize your data structure here. */
 7     public MovingAverage(int size) {
 8         window = new int[size];
 9         insert = 0;
10         sum = 0;
11     }
12     
13     public double next(int val) {
14         if (n < window.length)  n++;
15         sum -= window[insert];
16         sum += val;
17         window[insert] = val;
18         insert = (insert + 1) % window.length;
19         
20         return (double)sum / n;
21     }
22 }

 

posted @ 2016-12-15 09:54  neverlandly  阅读(392)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3