본문 바로가기

Computer General/Algorithm and Data Structure

Moving Average from Data Stream

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

 

class MovingAverage {
private:
    vector window;
    int capacity;
    int current_size;
    double sum;
    int start;
    int end;
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        this->capacity = size;
        this->current_size = 0;
        this->sum = 0;
        this->start = 0;
        this->end = 0;
    }
    
    double next(int val) {
        this->window.push_back(val);
        end = current_size++;
        sum += val;
        if(this->current_size > this->capacity)
        {
            sum -= window.at(start);
            start++;
            this->current_size--;
        }
        return this->sum / this->current_size;
    }
};

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

 

// using QUEUE

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size): _sum(0), _size(size) {
    }
    
    double next(int val) {
        _window.push(val);
        _sum += val;
        if(_window.size() > _size)
        {
            int front = _window.front();
            _window.pop();
            _sum -= front;
        }
        return _sum/_window.size();
    }
private:
    queue _window;
    double _sum;
    int _size;
};

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

'Computer General > Algorithm and Data Structure' 카테고리의 다른 글

Palindrome Permutation  (0) 2020.03.21
Intersection of Three Sorted Arrays  (0) 2020.03.21
Nested List Weight Sum  (0) 2020.03.21