File tree 2 files changed +29
-0
lines changed
2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change 322
322
547|[ Number of Provinces] ( ./0547-number-of-provinces.js ) |Medium|
323
323
551|[ Student Attendance Record I] ( ./0551-student-attendance-record-i.js ) |Easy|
324
324
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|
325
326
563|[ Binary Tree Tilt] ( ./0563-binary-tree-tilt.js ) |Easy|
326
327
565|[ Array Nesting] ( ./0565-array-nesting.js ) |Medium|
327
328
566|[ Reshape the Matrix] ( ./0566-reshape-the-matrix.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments