LintCode 604. Window Sum

题目

LintCode 604. Window Sum_第1张图片

思路

同向双指针

代码

class Solution:
    """
    @param nums: a list of integers.
    @param k: length of window.
    @return: the sum of the element inside the window at each moving.
    """
    def winSum(self, nums, k):
        # write your code here
        res_list = []
        if not nums: return []
        if k > len(nums): return []
        leftPoint = 0; rightPoint = k;
        sum = 0;
        for i in range(0, k):
            sum += nums[i]
        res_list.append(sum)
        while rightPoint < len(nums):
            sum += nums[rightPoint]
            sum -= nums[leftPoint]
            res_list.append(sum)
            rightPoint += 1
            leftPoint += 1
        return res_list

你可能感兴趣的:(OJ-LintCode,算法-双指针)