Given[-3, 1, 2, -3, 4]
, return[0, 2]
or[1, 3]
.
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
vector<int> results;
int size = nums.size();
if (size == 0) {
return results;
}
unordered_map<int, int> map;
// We set the index -1 sum to be 0 to let us more convient to count.
map.insert({0, -1});
int sum = 0;
for (int i = 0; i < size; i++) {
sum += nums[i];
if (map.find(sum) != map.end()) {
// For example:
// -3 1 2 -3 4
// SUM: 0 -3 -2 0 -3 1
// then we got the solution is : 0 - 2
results.push_back(map[sum]+1);
results.push_back(i);
return results;
} else {
map[sum] = i;
}
}
}
};