Title Description:
Given an array of integers and a integer K, you need to find the total number of continuous subarrays whose sum equals toK.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 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 integerk is [ -1e7, 1e7]. idea One (recursive solution): Total equals the number of k = the number of consecutive and equal to K as the first element in the array + in addition to the first element, the remaining elements are contiguous and equal to K, code reference:
public int subarraysum (int[] nums, int k) {
if (nums.length = = 1 && nums[0]! = k)
return 0;
Return Rescusum (Nums, K, 0);
}
private int rescusum (int[] nums, int k, int start) {
if (start >= nums.length) {
return 0;
}
int firstcount = 0;
int sum = 0;
for (int i = start; i < nums.length; ++i) {
sum + = nums[i];
if (sum = = k) {
++firstcount;
}
}
return Firstcount + rescusum (nums, K, start + 1);
}
thinking Two (no thought, hash mapping): Traverse all the starting point is the first element of the sub-sequence, called Sum[i], as long as the difference of two sum[i] is K, then two I as the beginning and end of the sub-sequence to meet the requirements. Since the starting point is the first element, simply traverse the end point and the time complexity is O (n)
public int subarraysum (int[] nums, int k) {
map<integer,integer> Map = new hashmap<integer,integer> (); C1/>map.put (0,1);
int sum = 0;
int res = 0;
for (int i = 0;i<nums.length;i++)
{
sum + = nums[i];
Res + = Map.getordefault (sum-k,0);
Map.put (Sum,map.getordefault (sum,0) +1);
}
return res;
}
idea Three: violence, time complexity O (n^2)