-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path138.subarray-sum.cpp
50 lines (47 loc) · 1.24 KB
/
138.subarray-sum.cpp
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
// Tag: Hash Table, Prefix Sum Array, Array
// Time: O(N)
// Space: O(N)
// Ref: -
// Note: -
// Given an integer array, find a subarray where the sum of numbers is **zero**.
// Your code should return the index of the first number and the index of the last number.
//
// **Example 1:**
//
// ```
// Input: [-3, 1, 2, -3, 4]
// Output: [0, 2] or [1, 3].
// Explanation: return anyone that the sum is 0.
// ```
//
// **Example 2:**
//
// ```
// Input: [-3, 1, -4, 2, -3, 4]
// Output: [1,5]
// ```
//
// There is at least one subarray that it's sum equals to zero.
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number and the index of the last number
*/
vector<int> subarraySum(vector<int> &nums) {
// write your code here
int n = nums.size();
int pre = 0;
unordered_map<int, int> table;
table[pre] = 0;
for (int i = 1; i <= n; i++) {
pre += nums[i - 1];
if (table.count(pre) > 0) {
return vector<int>{table[pre], i - 1};
} else {
table[pre] = i;
}
}
return vector<int>{-1, -1};
}
};