首页 > 其他 > 详细

LintCode "Subarray Sum"

时间:2015-09-04 07:34:10      阅读:243      评论:0      收藏:0      [点我收藏+]

sum[i..j] = sum[0..j] - sum[0..i-1]. We use a hashmap to check a previous matching index with a given number.

技术分享
class Solution {
public:
    vector<int> subarraySum(vector<int> nums){
        size_t len = nums.size();
        
        unordered_map<long, vector<int>> hm;
        
        vector<long> lsum(len);
        lsum[0] = nums[0];
        hm[lsum[0]].push_back(0);
        for(int i = 1 ; i < len; i ++)
        {
            lsum[i] = nums[i] + lsum[i - 1];
            hm[lsum[i]].push_back(i);
        }        
            
        vector<int> ret;
        for(int i = 0; i < len; i++)
        {
            if(lsum[i] == 0)
            {
                ret.push_back(0);
                ret.push_back(i);
                return ret;
            }
            else
            {
                if(hm.find(lsum[i]) != hm.end())
                {
                    if(!hm[lsum[i]].empty() && hm[lsum[i]][0] < i)
                    {
                        ret.push_back(hm[lsum[i]][0] + 1);
                        ret.push_back(i);    
                        return ret;
                    }
                }
            }
        }
        
        return ret;
    }
};
View Code

LintCode "Subarray Sum"

原文:http://www.cnblogs.com/tonix/p/4781194.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!