码迷,mamicode.com
首页 > 其他好文 > 详细

325 Maximum Size Subarray Sum Equals k

时间:2017-08-12 13:58:43      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:use   index   put   i++   current   hat   number   html   url   

Given an array nums and a target value k, find the maximum length of a subarray that sums to k.
If there isnt 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?

Like the other subarray sum problems Lintcode: Subarray Sum closest,  560. Subarray Sum Equals K523. Continuous Subarray Sum

Use a HashMap to keep track of the sum from index 0 to index i, use it as the key, and use the current index as the value

build the hashmap: scan from left to write, if the current sum does not exist in the hashmap, put it in. If the current sum does exist in Hashmap, do not replace or add to the older value, simply do not update. Because this value might be the left index of our subarray in later comparison. We are looking for the longest subarray so we want the left index to be the smaller the better. 

Every time we read a number in the array, we check to see if map.containsKey(num-k), if yes, try to update the maxLen.

考察对hashmap的value 的处理

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

  

325 Maximum Size Subarray Sum Equals k

标签:use   index   put   i++   current   hat   number   html   url   

原文地址:http://www.cnblogs.com/apanda009/p/7349948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!