码迷,mamicode.com
首页 > 其他好文 > 详细

3 - Two Pointers Algorithm

时间:2019-05-10 13:22:43      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:pointer   span   赋值   from   code   algo   元素   sum   ble   

604. Window Sum

https://www.lintcode.com/problem/window-sum/description?_from=ladder&&fromId=1

自己写的方法:

public int[] winSum(int[] nums, int k) {
        // write your code here
        int len = nums.length;
        if(nums == null || len < k || k <= 0) {
            return new int[0];
        }
        int[] result = new int[len - k + 1];
        int sum = 0;
        for(int i = 0; i < k; i++) {
            sum += nums[i];
        }
        result[0] = sum;
        for(int i = k; i < len; i++) {
            result[i - k + 1] = result[i - k] - nums[i - k] + nums[i];
        }
        return result;
    }

九章的答案:

public int[] winSum(int[] nums, int k) {
   // write your code here
  if (nums == null || nums.length < k || k <= 0)
      return new int[0];

    int[] sums = new int[nums.length - k + 1];
    // 计算nums的前k个数之和,赋值给sum[0]
    for (int i = 0; i < k; i++)
      sums[0] += nums[i];
    for (int i = 1; i < sums.length; i++) {
    // 减去头部元素,加上尾部元素
      sums[i] = sums[i - 1] - nums[i - 1] + nums[i + k-1];
    }
    return sums;
}

 

3 - Two Pointers Algorithm

标签:pointer   span   赋值   from   code   algo   元素   sum   ble   

原文地址:https://www.cnblogs.com/jenna/p/10843578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!