604.Window Sum

1.Decription(Easy)

Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find thesumof the element inside the window at each moving.

Example

For array[1,2,7,8,5], moving window size k =3. 1 + 2 + 7 = 10 2 + 7 + 8 = 17 7 + 8 + 5 = 20 return[10,17,20]

2.Code

设置存放结果的sums数组,先计算出sums[0],再从sums[1]开始,sums[i]=sums[i-1]-nums[i-1]+nums[i+k-1];剪去第一个数加上最后一个

 public int[] winSum(int[] nums, int k) {
        if(nums==null || nums.length<k || k<=0){
            return new int[0];
        }
        int[] sums=new int[nums.length-k+1];
        //Initialize the sum[0]
        for(int i=0;i<k;i++){
            sums[0]=sums[0]+nums[i];
        }
        //calculate from sums[i]
        for(int i=1;i<sums.length;i++){
            sums[i]=sums[i-1]-nums[i-1]+nums[i+k-1];
        }
        return sums;
    }

Last updated