Leetcode Everyday: 346. Moving Average from Data Stream
2016-05-11 20:53
453 查看
https://leetcode.com/problems/moving-average-from-data-stream/
Using LinkedList to maintain the data structure, keep track of the total value to improve the efficiency
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
public class MovingAverage { /** Initialize your data structure here. */ LinkedList<Integer> queue; int size; int total; public MovingAverage(int size) { queue = new LinkedList<Integer>(); this.size = size; total = 0; } public double next(int val) { if(queue.size()<size){ queue.add(val); total+=val; return (total+0.0)/queue.size(); }else{ total-=queue.remove(0); queue.add(val); total+=val; return (total+0.0)/size; } } } /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
Using LinkedList to maintain the data structure, keep track of the total value to improve the efficiency
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
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解