138. Subarray Sum

Code(Language:C++) (Judger:ip-172-31-12-4)
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
        unordered_map<int, int> mp;
        mp[0] = -1; 
        int prefixSum = 0; 
        for(int i = 0; i < nums.size(); i++){
            prefixSum += nums[i]; 
            if(mp.count(prefixSum)){
                return {mp[prefixSum] + 1, i}; 
            }
            mp[prefixSum] = i; 
        }
    }
};

Comments

Popular posts from this blog

算法的比较