leetcode Maximum Size Subarray Sum Equals k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.

Example 1:

Given nums = [1, -1, 5, -2, 3]k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)

Example 2:

Given nums = [-2, -1, 2, 1]k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)

Follow Up:

Can you do it in O(n) time?

首先看清题意是连续子数组,其次是要求时间复杂度为O(n),复杂度为O(n^2)的方法应该都是第一个想到的,这里就不写出来了,来看一下最优解吧:

首先这道题用到的思路和range sum有些类似,用一个sum变量记录数组前i项的和,如果和等于sum,那么长度加一,但此时的长度不一定是题目要求的最长子数组,因此还需要判断当前长度 和 和为sum的前i项减去和为sum-k的前j项的差哪一个长度较大(前提当然是和为sum-k项存在,因此需要一个hashmap进行搜索),还需要注意到一个细节时采用hashmap进行搜索是不能出现重复的sum的,但是实际数组中是可能出现的,这时我们只保留第一次出现该sum时的索引以保证最大长度,这个比较好理解。代码:

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

和为0的索引需要提前put进去,否则当中途出现第一个sum为0的索引时会把该索引put进去,结果显然是不正确的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值