Window Sum

思路:
一看到求连续sum的就要考虑prefixsum。
代码如下:


 public 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.  
    */  
   public int[] winSum(int[] nums, int k) {  
     // write your code here  
     int[] preSum = new int[nums.length + 1];  
     List<Integer> list = new ArrayList<>();  
     for(int i = 1; i <= nums.length; i++)   
     {  
       preSum[i] = preSum[i-1] + nums[i-1];  
       if(i >= k) {  
         list.add(preSum[i] - preSum[i - k]);  
       }  
     }  
     int[] res = new int[list.size()];  
     int i = 0;  
     for(int n: list)  
     {  
       res[i++] = n;  
     }  
     return res;  
   }  
 }  

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array