Skip to content

Commit c59c259

Browse files
committed
Create: 0560-subarray-sum-equals-k
1 parent 21ca8e2 commit c59c259

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var subarraySum = function (nums, k) {
7+
let count = 0,
8+
sum = 0,
9+
map = new Map();
10+
map.set(0, 1);
11+
for (const num of nums) {
12+
sum += num;
13+
if (map.has(sum - k)) {
14+
count += map.get(sum - k);
15+
}
16+
map.set(sum, (map.get(sum) || 0) + 1);
17+
}
18+
return count;
19+
};

rust/0560-subarray-sum-equals-k.rs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
use std::collections::HashMap;
2+
impl Solution {
3+
pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
4+
let (mut count, mut sum, mut map) = (0, 0, HashMap::with_capacity(nums.len() / 2));
5+
map.insert(0, 1);
6+
for num in nums {
7+
sum += num;
8+
count += map.get(&(sum - k)).copied().unwrap_or(0);
9+
map.entry(sum).and_modify(|e| *e = *e + 1).or_insert(1);
10+
}
11+
count
12+
}
13+
}
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function subarraySum(nums: number[], k: number): number {
2+
let count = 0,
3+
sum = 0,
4+
map = new Map<number, number>();
5+
map.set(0, 1);
6+
for (const num of nums) {
7+
sum += num;
8+
if (map.has(sum - k)) {
9+
count += map.get(sum - k);
10+
}
11+
map.set(sum, (map.get(sum) || 0) + 1);
12+
}
13+
return count;
14+
}

0 commit comments

Comments
 (0)