Labels

Saturday, February 21, 2015

Sliding Window Sum

Given a list of integers and a window size, return a new list of integers where each integer is the sum of all integers in the kth window of the input list. The kth window of the input list is the integers from index k to index k + window size - 1(inclusive).

For example, [1, 2, 3, 4] and window size 3 should return [6,9].

Naive Thinking: 用一个var标记当前和,每次前进一步都减头部加尾部。

算法复杂度是O(n)。

public class Solution{

    public static void main(String args[]){
        Solution s = new Solution();
        int num[] = {1,2,4,6};
        int sums[] = s.slidingWindowSum(num,4);
        for(int i = 0;i < sums.length;i++)
            System.out.print(sums[i] + " ");
        System.out.println();
    }

    public int[] slidingWindowSum(int num[], int window_size){
        // initialize result
        int sums[] = new int[Math.max(num.length-window_size+1,1)];
        // check if window_size is greater than num[] size, return -1
        if(window_size > num.length) sums[0] = -1;
        // current sum, function as a window
        int cur_sum = 0;
        // go through num[]
        for(int i = 0, j = 0;i < num.length;i++){
            // each time a new number come, add to window
            cur_sum += num[i];
            if(i >= window_size-1){
                // if not the start window, delete the first one from window
                if(i-window_size >= 0) cur_sum -= num[i-window_size];
                // set window(cur_sum) to output
                sums[j++] = cur_sum;
            }
        }
        return sums;
    }
}

No comments:

Post a Comment