Leetcode 560
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:
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, 1000] and the range of the integer k is [-1e7, 1e7].
方法
public class Solution {
public int subarraySum(int[] nums, int k) {
}
}
解答
1. Brute Force (start-end)
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
return count;
}
}
(time limit exceeded)
2. cumulative sum (累加和)
注意连续二字
sum[i] 表示nums中前i个数之和
sum[j] - sum[i] (j>i)表示i~j的累加和
所以先求出sum[i]
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int[] sum = new int[nums.length];
for(int i=0;i<nums.length;i++){
if(i==0)sum[i]=nums[i];
else{
sum[i]=sum[i-1]+nums[i];
}
if(sum[i]==k)count++;
}
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(sum[j]-sum[i] == k)count++;
}
}
return count;
}
}
accepted
3. Start-End pro
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
for(int start=0;start<nums.length;start++)
{
int sum = 0;
for(int end=start;end<nums.length;end++)
{
sum += nums[end];
if(sum == k)count++;
}
}
return count;
}
}
4. HashMap
前几个方法都还不错,但时间上很昂贵。
在累加和方法的基础上,使用HashMap存储
key: 累加和的值,value: 所求累加和为该值的个数
sum[i] = sum[j]-k,使用HashMap查询sum-k的值是否存于HashMap中
若存在,count值加上sum-k对应的value值。
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
hashmap.put(0,1); // 0,一个也不加
int sum=0;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
if(hashmap.containsKey(sum-k)){
count += hashmap.get(sum-k);
}
hashmap.put(sum, hashmap.getOrDefault(sum,0)+1);
}
return count;
}
}
由上到下:4,3,2,1方法时间对比