-
Notifications
You must be signed in to change notification settings - Fork 91
/
Subarray_Sum_Equals_K.js
58 lines (48 loc) · 1.21 KB
/
Subarray_Sum_Equals_K.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Subarray Sum Equals K
https://leetcode.com/problems/subarray-sum-equals-k/
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
// Solution 1
var subarraySum = function (nums, k) {
var ret = 0;
for (var i = 0; i < nums.length; i++) {
var count = 0;
for (var j = i; j < nums.length; j++) {
count += nums[j];
if (count === k) ret++;
}
}
return ret;
};
// Solution 2
var subarraySum2 = function (nums, k) {
if (nums.length === 0) return 0;
var sums = [];
sums[0] = 0;
var count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
sums[i + 1] = count;
}
var ret = 0;
for (i = 0; i < sums.length - 1; i++) {
for (var j = i + 1; j < sums.length; j++) {
if (sums[j] - sums[i] === k) ret++;
}
}
return ret;
};
module.exports.subarraySum = subarraySum;
module.exports.subarraySum2 = subarraySum2;