classMovingAverage {privateint sum;privateQueue<Integer> queue;privateint capacity; /** Initialize your data structure here. */publicMovingAverage(int size) { queue =newLinkedList<Integer>(); sum =0; capacity = size; }publicdoublenext(int val) {if (queue.size() == capacity) {int sub =queue.poll(); sum = sum - sub; }queue.offer(val); sum = sum + val;return (double) sum /queue.size(); }}/** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
Another simplerimplementation using LinkedList as Queue
classMovingAverage {Queue<Integer> q;double sum =0;int size;publicMovingAverage(int s) { q =newLinkedList(); size = s; }publicdoublenext(int val) {if(q.size() == size){ sum = sum -q.poll(); }q.offer(val); sum += val;return sum/q.size(); }}
Using ArrayDeque
classMovingAverage {Deque<Integer> q;int sum;int size; /** Initialize your data structure here. */publicMovingAverage(int size) {this.size= size; sum =0; q =newArrayDeque<Integer>(); }publicdoublenext(int val) {if (size ==q.size()) { sum -=q.poll(); } sum += val;q.offer(val);return1.0* sum /q.size(); }}/** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
Using fixed length Array (Circular Queue)
(74 ms, faster than 100.00%, 43 MB, less than 59.43%)