346. Moving Average from Data Stream
346. Moving Average from Data Stream //I’m not familiar with initializing instance var and use them under constructor class MovingAverage { /** Initialize your data structure here. */ private int maxSize; // use private? Why private double sum = 0.0; // here uses double private Queue<Integer> queue; public MovingAverage(int size) { queue = new LinkedList<Integer>(); maxSize = size; } public double next(int val) { // returns the average so far if(queue.size() == maxSize){ sum = sum - queue.poll(); } queue.offer(val); sum += val; double average = sum / queue.size(); return average; } }
the next() func takes in an integer,
First check if the queue size() == maxSize
if it’s the same, then we poll the top, which is the one we added first .update the sum , sum - queue.poll()
And offer the new one from the bottom , update the sum , sum + queue.poll()
And calculate the average
If it’s not the same, then we can just offer the new element and update the same
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
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
posted on 2018-08-10 14:38 猪猪🐷 阅读(145) 评论(0) 收藏 举报
浙公网安备 33010602011771号