问题描述:
给你一个整数数组
nums
和一个整数k
,请你统计并返回 该数组中和为k
的子数组的个数 。子数组是数组中元素的连续非空序列。示例 1:
输入:nums = [1,1,1], k = 2 输出:2示例 2:
输入:nums = [1,2,3], k = 3 输出:2解题思路:
560. 和为 K 的子数组 - 力扣(LeetCode)https://leetcode.cn/problems/subarray-sum-equals-k/solutions/238572/he-wei-kde-zi-shu-zu-by-leetcode-solution/?envType=study-plan-v2&envId=top-100-liked
//提交版
//注释掉的为暴力搜索版本
class Solution {
public int subarraySum(int[] nums, int k) {
// int count = 0;
// for (int i = 0; i < nums.length; i++) {
// int sum = 0;
// for (int j = i; j >= 0; j--) {
// sum = sum + nums[j];
// if (sum == k) {
// count++;
// }
// }
// }
// return count;
HashMap<Integer,Integer> hashMap = new HashMap<>();
hashMap.put(0,1);
int pre =0;
int count =0;
for (int i =0;i<nums.length;i++){
pre = pre + nums[i];
if (hashMap.containsKey(pre-k)){
count = count + hashMap.get(pre-k);
}
hashMap.put(pre,hashMap.getOrDefault(pre,0)+1);
}
return count;
}
}
//带有输入输出版本
import java.util.Arrays;
import java.util.HashMap;
public class hot9_subarraySum {
public int subarraySum(int[] nums, int k) {
// int count = 0;
// for (int i = 0; i < nums.length; i++) {
// int sum = 0;
// for (int j = i; j >= 0; j--) {
// sum = sum + nums[j];
// if (sum == k) {
// count++;
// }
// }
// }
// return count;
HashMap<Integer,Integer> hashMap = new HashMap<>();
hashMap.put(0,1);
int pre =0;
int count =0;
for (int i =0;i<nums.length;i++){
pre = pre + nums[i];
if (hashMap.containsKey(pre-k)){
count = count + hashMap.get(pre-k);
}
hashMap.put(pre,hashMap.getOrDefault(pre,0)+1);
}
return count;
}
public static void main(String[] args){
int[] nums = {3,4,7,2,-3,1,4,2};
int k = 7;
System.out.println("输入:" + Arrays.toString(nums)+"\t"+ "k="+k);
hot9_subarraySum hot9SubarraySum = new hot9_subarraySum();
int result = hot9SubarraySum.subarraySum(nums,k);
System.out.println("输出:"+result);
}
}
知识点总结:
- 前缀+哈希表的解题思路(理解不透彻,二刷时注意)