Given an array of integers and a integer k, you need to find the total number of continuous subarrays whose sum equals to K.
Example 1:
Input:nums = [1,1,1], k = 2output:2
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [ -1000, +] and the range of the integer k is [ -1e7, 1e7].
Title Tags: Array, Map
The topic gives us a nums array and a K, to find out how many of the sub-arrays are equal to K.
The first thought was the brute force solution, though it was able to pass, but N*n was always too slow.
This problem can be used HashMap, the occurrence of sum as a key deposit, the sum of the number of occurrences as value deposit.
Traverse nums array, always update sum, and then go to map to find there is no sum-k, some words that sum-k is an old sum, before appeared. In other words, the new sum-the old sum = K-Indicates the new sum minus the old sum, the sum of the remaining section equals K, and finds a subarray of sum = k. The new sum is then deposited into the map.
The key to this problem is that when we know a sum (0,i) and sum (0,j), we know Sum (i+1, J).
So when we know all the old sums now, when we have a new sum, we can use the map to find out if the new sum-k are in the map. Once present, it shows that we found a sub-array of its and for K.
Note that the Count + here is the value in the map, not the count++, because when you find a sum-k old sum in the map, the old sum may have occurred 2 times, in other words, there may be two different lengths of sub-arrays, but their sum is equal to Sum-k (because there are negative numbers). So here is the number of occurrences of the old sum 2, because you have found two different sub-arrays whose sum is K.
Java Solution:
Runtime beats 67.25%
Completion Date: 10/03/2017
Keywords: Array, HashMap
Key points: All occurrences of sum are deposited map:sum as key, the number of occurrences is value; use Map to find K (new sum-k =? Any old sum)
1 classSolution2 {3 Public intSubarraysum (int[] Nums,intk)4 {5 intCount = 0;6 intsum = 0;7 8Map<integer, integer> map =NewHashmap<>();9Map.put (0, 1);//initial value sum = 0, occurrence = 1 for case sum = k, k-k = 0 countsTen One for(inti=0; i<nums.length; i++)//Iterate nums Array A { -Sum + = Nums[i];//Update Sum - the if(Map.containskey (SUM-K))//If map has sum-k, meaning this new sum-old sum = k -Count + = Map.get (sum-k);//previous sum might appear more than once - //This is why we need to add its value -Map.put (sum, map.getordefault (sum, 0) + 1);//save new sum into map + } - + returncount; A } at}
Resources:
Https://discuss.leetcode.com/topic/87850/java-solution-presum-hashmap
Leetcode List of topics- leetcode Questions List
Leetcode 560. Subarray Sum equals K (the sum of the sub-arrays equals K)