问题描述(难度中等)
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
1 | Input:nums = [1,1,1], k = 2 |
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
方法一:递归
可以拆解为多个子问题。通过递归的方式求解,时间复杂度O(N^2),空间复杂度O(1)。
1 | package P560; |
方法二:HashMap
通过map存储和出现的次数,key为[0,j]元素的和,value为和出现的次数。假设[i,j]为和为k的数组,那么sum(0,j)-k=sum(0,i)。时间复杂度O(N),空间复杂度O(N)。
1 | package P560; |
总结
通过Map可以以空间换取时间。