子串

子串

Jason Lv3

560. 和为K的子数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//看了答案思路写的
class Solution {
public int subarraySum(int[] nums, int k) {
int sum[] = new int[nums.length+1];
sum[0]=0;
int count=0;
//统计前面出现的次数
for(int i=1;i<sum.length;i++){
sum[i] = sum[i-1]+nums[i-1];

}
//遍历数组,求出每个元素和为k的子数组的个数
for(int end=1;end<sum.length;end++){
for(int start=1;start<=end;start++){
if(sum[end]-sum[start-1]==k) count++;
}

}
return count;

}
}

//官方解
//使用了两数之和的做法
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0, pre = 0;
HashMap < Integer, Integer > mp = new HashMap < > ();
mp.put(0, 1);
//统计前面出现的次数
for (int i = 0; i < nums.length; i++) {
pre += nums[i];
if (mp.containsKey(pre - k)) {
count += mp.get(pre - k);
}
mp.put(pre, mp.getOrDefault(pre, 0) + 1); //统计前面出现的次数
}
return count;
}
}


  • Title: 子串
  • Author: Jason
  • Created at : 2023-09-17 20:06:52
  • Updated at : 2023-09-18 20:45:26
  • Link: https://xxxijason1201.github.io/2023/09/17/LeetCode/子串/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments
On this page
子串