zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    1001. 害死人不偿命的(3n+1)猜想 (15)
    单链表排序
    简单插入排序
    简单选择排序
    C语言-随机数
    二分查找(折半查找)
    顺序查找-顺序查找-带哨兵查找
    队列-链表实现
    循环队列_数组实现
    队列-顺序存储-简单实现
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6182056.html
Copyright © 2011-2022 走看看