[Leetcode] Moving Average from data stream moving an average from a stream

Source: Internet
Author: User

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

This problem defines a MovingAverage class, which can be stored in a fixed number, and then each time we read a number, if the total number after adding this number is greater than the number of limits, then we remove the first number entered, and then return the updated average, This FIFO feature works best with queue queues, and we also need a double variable sum to record the sum of all current numbers so that if there are no more than the limit, then sum is added to the number, and if it is exceeded, sum subtracts the first number first. Add this number and then return the sum divided by the number of queues:

classMovingAverage { Public: MovingAverage (intsize) {         This->size =size; Sum=0; }        DoubleNextintval) {        if(Q.size () >=size) {Sum-=Q.front (); Q.pop ();        } Q.push (Val); Sum+=Val; returnSum/q.size (); }    Private: Queue<int>Q; intsize; Doublesum;};

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Moving Average from data stream moving an average from a stream

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.