LintCode Subarray Sum

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.
Have you met this question in a real interview? Yes
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.

卡了一会,需要求一个sum = sigma(a[0]..a[i])的累加和,因为如果某个subarray是0的话,就会出现有两个累加和相同的请求。比如上面例子中的累加和:

-3 -2 0 -3 -1

可以看到有两个-3,也就是说在这两者之间其subarray和为0,才导致了两个位置累加和重叠。还有一种简单的情况就是碰到摸个累加和为0,那么也就是说从数组开始到当前位置的和为0。

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 len = nums.size();
        vector<int> res;
 
        int sum = 0;
    
        unordered_map<int, int> val2idx;
        
        for (int i = 0; i < len; i++) {
            sum += nums[i];
            if (sum == 0) {
                res = {0, i};
                return res;
            }
            if (val2idx.count(sum) > 0) {
                res = {val2idx[sum] + 1, i};
                break;
            }
            val2idx[sum] = i;
        }
        
        return res;
    }
};

感觉放在easy等级里不合适

posted @ 2015-09-12 00:17  卖程序的小歪  阅读(159)  评论(0编辑  收藏  举报