题解 | #哈希+前缀和系列#

未排序数组中累加和为给定值的最长子数组长度

http://www.nowcoder.com/practice/704c8388a82e42e58b7f5751ec943a11

专题系列

https://leetcode-cn.com/problems/find-longest-subarray-lcci/solution/qian-zhui-he-ha-xi-by-louris-10h7/

class Solution {
public:
    /**
     * max length of the subarray sum = k
     * @param arr int整型vector the array
     * @param k int整型 target
     * @return int整型
     */
    int maxlenEqualK(vector<int>& arr, int k) {
        // write code here
        int n = arr.size();
        unordered_map<int, int> ump;
        ump[0] = -1;
        int ans = 0;
        int sum = 0;
        for(int i = 0 ; i < n; i ++){
            sum += arr[i];
            if(ump.find(sum - k) != ump.end()){
                ans = max(ans, i - ump[sum - k]);
            }
            if(ump.find(sum) == ump.end()) ump[sum] = i; //如果不存在,则更新,保证同一个前缀sum记录的是最小的索引
        }
        return ans;
    }
};
全部评论

相关推荐

king327:最好要在简历中很好地包装和证明你的能力 要证明你的技术深度才能在面试官那里有竞争力 如果你有需要的话可以看一下我主页简历我帮你详细地说一下各个地方的具体问题
实习简历求拷打
点赞 评论 收藏
分享
昨天 22:36
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务