码迷,mamicode.com
首页 > 编程语言 > 详细

325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组

时间:2018-05-13 12:00:43      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:ons   分治   contains   ima   中间   find   pac   shm   code   

[抄题]:

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.

Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

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?

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

以为只有max(max, a)才能取最长,不知道怎么写。其实就是一般思路 sum随着i增加而变长,把i给for一遍就行了。

[一句话思路]:

gap中一下子增加了k时,index也取对应值即可

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

技术分享图片

[一刷]:

  1. map.containsKey(sum)没用,必须要sum == k才行

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

必须考虑中间的gap. gap中一下子增加了k时,index也取对应值即可

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

常量sum才能累加,数组不能:

sum[i] += nums[i]; 相当于每个数都重新加了

[算法思想:递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

2 sum: hashmap

 [代码风格] :

技术分享图片
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        //cc
        if (nums == null || nums.length == 0) return 0;
        
        //ini: hashmap, max
        HashMap<Integer, Integer> map = new HashMap<>();
        int max = 0, sum = 0;
        
        //for loop: 3 conditions
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            //contains, gap, not contains
            if (sum == k) max = i + 1;
            else if (map.containsKey(sum - k)) max = Math.max(max, i - map.get(sum - k));
            
            if (!map.containsKey(sum)) map.put(sum, i);
        }
        
        return max;
    }
}
View Code

 

325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组

标签:ons   分治   contains   ima   中间   find   pac   shm   code   

原文地址:https://www.cnblogs.com/immiao0319/p/9031286.html

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