Window Sum

solution

给一个数组[1, 2, 3, 4, 5] 和 3 输出[6, 9, 12] sliding window

code

// Example program
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<int> windowsum(vector<int>& win, int k)
{
    vector<int> ret;
    int sum = 0;

    for(int i = 0; i<k-1; i++)
    {
        sum += win[i];   
    }

    int n = (int)win.size();
    for(int i = k-1; i<n; i++)
    {
        sum += win[i];
        ret.push_back(sum);
        sum -= win[i-k+1];
    }

    return ret;
}

int main()
{
    vector<int> win;
    win.push_back(1);
    win.push_back(2);
    win.push_back(100);
    win.push_back(5);
    win.push_back(200);
    win.push_back(1);
    win.push_back(2);
    win.push_back(3);

    vector<int> ret = windowsum(win, 3);
    for(int i = 0; i<(int)ret.size(); i++)
    {
        cout<<ret[i]<<" ";   
    }
    return 1;
}

results matching ""

    No results matching ""