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?

思路:木有想出来。参考了dicussion。

大概是这样的想法:指针从左往右扫,记录sum。看sum是不是等于k。这时候我们就疑惑怎么解决sum里面的组合。用sum-k。就是 [a,b,c,d,e,f,g] 如果指针扫到g是sum[g], 如果存在sum[i]==sum[g]-k那么我们就知道sum[i]右边一直加到sum[g]和等于k。这样就能找到对应的长度。比较tricky。

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

 

posted on 2016-09-27 14:51  Machelsky  阅读(148)  评论(0)    收藏  举报