Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 6349f15

Browse files
committedFeb 20, 2025
Add solution #560
1 parent e8bf6ca commit 6349f15

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,7 @@
322322
547|[Number of Provinces](./0547-number-of-provinces.js)|Medium|
323323
551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy|
324324
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|
325+
560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium|
325326
563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy|
326327
565|[Array Nesting](./0565-array-nesting.js)|Medium|
327328
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 560. Subarray Sum Equals K
3+
* https://leetcode.com/problems/subarray-sum-equals-k/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers nums and an integer k, return the total number of subarrays
7+
* whose sum equals to k.
8+
*
9+
* A subarray is a contiguous non-empty sequence of elements within an array.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums
14+
* @param {number} k
15+
* @return {number}
16+
*/
17+
var subarraySum = function(nums, k) {
18+
const map = new Map([[0, 1]]);
19+
let result = 0;
20+
21+
for (let i = 0, count = 0; i < nums.length; i++) {
22+
count += nums[i];
23+
result += map.get(count - k) ?? 0;
24+
map.set(count, (map.get(count) ?? 0) + 1);
25+
}
26+
27+
return result;
28+
};

0 commit comments

Comments
 (0)
Please sign in to comment.