• LintCode "Subarray Sum"


    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
  • 相关阅读:
    视图容器组件使用
    组件的学习
    伸展树
    二叉搜索树
    二叉树
    笛卡尔树
    二叉堆
    vim配置
    使用vim-pathogen 进行插件管理
    C/C++中的变量和静态变量
  • 原文地址:https://www.cnblogs.com/tonix/p/4781194.html
Copyright © 2020-2023  润新知