LeetCode560 subarray size equals K

we need to count the number of subarray of a given array that the sum equals to K.

first, brute force, and we can easily write it in O(n^2)

and there is actually a good way to calculate the sum of subarray in O(1) time. (well, not O(1) atually), and we use space-time trade off by using the culmultive sum[]. like following code:
for (int i = 1; i <= nums.length; i++)
sum[i] = sum[i - 1] + nums[i - 1];

and even thought the leetcode provide 4 ways for this problem, but the first three are actually both brute force.

and the way that can solve this problem in O(n) time is using hashmap:

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0, sum = 0;
        HashMap <Integer, Integer> map = new HashMap <> (); //key is culmutive of nums and value is the times this culmutive value appears
        //the next codes remains me of another problem, which we contruct the hashmap and the final results at the same time. still not fully understand, LC352
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i]; //each for loop, sum is the sum of first i elements in nums
            if (map.containsKey(sum - k))
                count += map.get(sum - k);
            map.put(sum, map.getOrDefault(sum, 0) + 1); //
        }
        return count;
    }
}
posted @ 2020-05-16 15:05  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报