Easy C solution


  • 0
    L

    Keep past numbers in an array and add the new one before calculating average.

    typedef struct {
        int weight;
        int window;
        int *past_numbers;
    } MovingAverage;
    
    /** Initialize your data structure here. */
    MovingAverage* movingAverageCreate(int size) {
        MovingAverage *obj = (MovingAverage *) calloc (1, sizeof (MovingAverage));
    
        obj->window = size;
        obj->past_numbers = (int *) calloc (size, sizeof (int));
    
        return obj;
    }
    
    double movingAverageNext(MovingAverage* obj, int val) {
        int tmp = 0;
    
        if (obj->weight < obj->window) {
            obj->past_numbers[obj->weight] = val;
            obj->weight = obj->weight + 1;
        } else {
            for (int n = 0; n < (obj->window - 1); n++)
                obj->past_numbers[n] = obj->past_numbers[n + 1];
        
            obj->past_numbers[obj->window - 1] = val;
        }
    
        for (int n = 0; n < obj->weight; n++) {
            tmp += obj->past_numbers[n];
        }
        return (double) tmp / obj->weight;
    }
    
    void movingAverageFree(MovingAverage* obj) {
        free (obj->past_numbers);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.