亚麻:window sum

这是亚麻的OA 题。

一个滑动窗遍历数组,求滑动窗再每个时刻的和

 

#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector
#include <unordered_map>
#include <numeric>

//key point
//slide window, memorize the sum of the current window, while move one step, add the difference between the new one and the oldest one.

std::vector<int> winSum (std::vector<int>&& nums, int&& k){
    // check pararmeters.
    if ( nums.size () ==0 || k <1 || k > nums.size()) return std::vector<int>();
    int steps = k -1;
    
    int sum = std::accumulate(nums.begin(),nums.begin()+k, 0);
    std::vector<int> res ;
    res.push_back(sum);
    
    int start = 1;
    int end = start + steps;
    
    while (end < nums.size()-1){
        sum += (nums[end]- nums[start-1]);
        res.push_back(sum);
        start++;
        end ++;
    }
    
    return res;
}

int main () {
    
    std::vector<int> && out = winSum ({1,2,3,4,5,6,7,8},3);
    for (auto e: out)
        std::cout<< e << " " ;
    
    return 0;
}

 

posted @ 2018-01-17 07:54  HisonSanDiego  阅读(284)  评论(0编辑  收藏  举报