【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日