【LeetCode】325.Maximum Size Subarray Sum Equals k(Medium)解题报告

65 篇文章 0 订阅

【LeetCode】325.Maximum Size Subarray Sum Equals k(Medium)解题报告

题目地址:https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/(带锁题)
题目描述:

  https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/
  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?

  类似于two sum。
  1 -1 5 -2 3 k=3
  1 0 5 3 6 k=3
  0 -1
  1 0
  //0 1
  5 1
  3 2
  6 3
  很tricky的地方,map先入0 -1,为了最大长度后面不是else,不能更新。

Solution:

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

Date:2018年2月18日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值