亚麻: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;
}

 

转载于:https://www.cnblogs.com/HisonSanDiego/p/8300831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值