标签: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;
}
标签:pointer span 赋值 from code algo 元素 sum ble
原文地址:https://www.cnblogs.com/jenna/p/10843578.html