346. Moving Average in Data Stream

Given an integer data stream and a window size, calculate the moving average of all integers according to the size of the sliding window.

For detailed topics, please view leetcode https://leetcode-cn.com/problems/moving-average-from-data-stream/

Problem-solving ideas The
problem is not very clear, and the final output is the average of the numbers in the sliding window. The specific method is to use a queue. When the queue length is less than the sliding window value, the average number in the queue can be calculated. When the queue length is greater than the sliding window value, pop up a suitable number of elements at the head of the queue (the sliding window takes the elements at the end of the queue), and then calculate the average value.

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        maxlen = size;
    }
    
    double next(int val) {
        q.push(val);
        if(q.size()>maxlen){
            for(int i = 0;i<q.size()-maxlen;i++){
                q.pop();
            }
        }
        int temp = 0;
        for(int i = 0;i<q.size();i++){
            temp += q.front();
            q.push(q.front());
            q.pop();
        }
        return (double)temp/q.size(); 
    }

private:
    queue<int> q;
    int maxlen;
};

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage* obj = new MovingAverage(size);
 * double param_1 = obj->next(val);
 */

作者:rasotae
链接:https://leetcode-cn.com/problems/moving-average-from-data-stream/solution/346-shu-ju-liu-zhong-de-yi-dong-ping-jun-ijs1/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

Guess you like

Origin blog.csdn.net/wyzworld/article/details/112249085