`

LintCode - Subarray Sum Zero

阅读更多

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

Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

Note

There is at least one subarray that it's sum equals to zero. 

 

vector<int> subarraySum(vector<int> nums){
    unordered_map<int, int> map;
    map[0] = -1;
    int sum = 0;
    vector<int> res(2);
    for(int i=0; i<nums.size(); i++) {
        sum += nums[i];
        if(map.count(sum) != 0) {
            res[0] = map[sum]+1;
            res[1] = i;
            return res;
        }
        map[sum] = i;
    }
    return res;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics