Window Sum – Python 3 (Week 10 – 10)

Solution 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
        ans = []
        
        if len(nums) == 0 or len(nums) < k or k <= 0: return ans
        
        sum = 0
        
        for i in range(k):
            sum += nums[i]
            
        ans.append(sum)
            
        
        for i in range(k, len(nums),):
            sum -= nums[i - k]
            sum += nums[i]
            ans.append(sum)
            
        return ans

Time O(n). Space O(1).

Solution 2

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
        n = len(nums)
        if n < k or k <= 0:
            return []
        sums = [0] * (n - k + 1)
        for i in range(k):
            sums[0] += nums[i];

        for i in range(1, n - k + 1):
            sums[i] = sums[i - 1] - nums[i - 1] + nums[i + k - 1]

        return sums

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started