一、题目描述
二、示例
三、难度
中等
四、代码
Java版
4.1 法一:前缀和解法
时间复杂度O(n2)
package per.Kidd.demo;
public class Solution {
private int[] preSum;
public void print() {
for(int arr : preSum) {
System.out.print(arr+" ");
}
}
public int subarraySum(int[] nums, int k) {
int count = 0;
preSum = new int[nums.length + 1];
for(int i = 1; i <= nums.length; ++i) {
preSum[i] = nums[i - 1] + preSum[i - 1];
}
for(int i = 0; i < preSum.length; ++i) {
for(int j = i + 1; j < preSum.length; ++j) {
if(preSum[j] - preSum[i] == k) ++count;
}
}
return count;
}
public static void main(String[] args) {
int[] nums = {1,-1,0};
int k = 0;
Solution s = new Solution();
System.out.println(s.subarraySum(nums, k));
s.print();
}
}
4.2 法二:前缀和 + 哈希表优化
时间复杂度O(n)
import java.util.HashMap;
import java.util.Map;
public class Solution {
private Map<Integer,Integer> preSumMap;
public int subarraySum(int[] nums, int k) {
preSumMap = new HashMap<>();
preSumMap.put(0,1);
int arraySum = 0;
int count = 0;
for(int i = 0; i < nums.length; ++i) {
arraySum += nums[i];
int key = arraySum - k;
if(preSumMap.containsKey(key)) {
count += preSumMap.get(key);
}
if(preSumMap.containsKey(arraySum)) {
preSumMap.put(arraySum, preSumMap.get(arraySum) + 1);
}
else preSumMap.put(arraySum, 1);
}
return count;
}
public static void main(String[] args) {
int[] nums = {1,2,1,2,1};
int k = 3;
Solution s = new Solution();
System.out.println(s.subarraySum(nums, k));
}
}
|