Tuesday, March 7, 2017

Window Sum

int[] result = new int[0]; //is allowed
It is for reducing null checks. You can iterate on an empty array but you can't iterate on null.
Reference from Jiuzhang https://www.jiuzhang.com/solutions/window-sum/
这道题我理所当然地用了PrefixSum的方法,先把整个数组遍历一遍求出PrefixSum,然后再遍历一遍求sum。
然而实际上这道题不用这么复杂,看了九章的解法,就是直接求出前k个数的和,然后遍历的过程中每次加入后一个数并减去前一个数,这样只要把整个数组遍历一遍即可。非常简单。

My own code:
public class Solution {
    /**
     * @param nums a list of integers.
     * @return the sum of the element inside the window at each moving.
     */
    public int[] winSum(int[] nums, int k) {
        // write your code here
        if (nums == null || nums.length == 0 || k <= 0) {
            return new int[0];
        }
        int[] prefixSum = new int[nums.length + 1];
        prefixSum[0] = 0;
        int sum = 0;
        for (int i = 1; i < prefixSum.length; i++) {
            sum += nums[i - 1];
            prefixSum[i] = sum;
        }
        int[] result = new int[nums.length - k + 1];
        for (int j = 0; j < result.length; j++) {
            result[j] = prefixSum[j + k] - prefixSum[j];
        }
        return result;
    }
}

No comments:

Post a Comment