Maximum Size Subarray Sum Equals k

本文介绍了一种求解给定数组中和为特定值的最长连续子数组长度的方法。通过使用哈希表记录前缀和及其对应的最早位置,可以在O(n)的时间复杂度内解决问题。文章提供了一个Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一道很有意思的题,我们的确要从中找出通用的解法,

注意:

map.put(0, -1);

这个有奇效,不仅仅是

Note the map.put(0, -1). We need to put this entry into the map before, because if the maximal range starts from 0, we need to calculate sum(j) - sum(i - 1). 

public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        Map<Integer, Integer> map = new HashMap<>();
        int max = 0;
        int sum = 0;
        map.put(0, -1);
        for(int i = 0; i < nums.length; i++) {
            sum = sum + nums[i];
            if (!map.containsKey(sum)) {
                map.put(sum, i);
            }
            if (map.containsKey(sum - k)) {
                int preIndex = map.get(sum - k);
                max = Math.max(max, i - preIndex);
            }
        }
        return max;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值