Given an integer array, find a subarray where the sum of numbers iszero. Your code should return the index of the first number and the index of the last number.

Notice

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

Have you met this question in a real interview?

Yes

Example

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

line 21, don't forget to update hashmap

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> res;

    unordered\_map<int,int> hashmap;

    hashmap\[0\] = -1;

    int sum = 0;

    for \(int i = 0; i < nums.size\(\); ++i\) {

        sum += nums\[i\];

        if \(hashmap.find\(sum\) != hashmap.end\(\)\) {

            res.push\_back\(hashmap\[sum\] + 1\);

            res.push\_back\(i\);

            return res;

        }

        hashmap\[sum\] = i;

    }



    return res;

}

};

results matching ""

    No results matching ""