3 - Two Pointers Algorithm
Posted jenna
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3 - Two Pointers Algorithm相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章