LeetCode 325. Maximum Size Subarray Sum Equals k

原题链接在这里:https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/

题目:

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:

Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4 
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Example 2:

Input: nums = [-2, -1, 2, 1], k = 1
Output: 2 
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

Follow Up:
Can you do it in O(n) time?

题解:

用HashMap记录<sum, index> pair. 遇到sum-k在HashMap中时说明从hm.get(sum-k) 到 i 这一段的和是k.

Time Complexity: O(n). n = nums.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int maxSubArrayLen(int[] nums, int k) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         
 7         int sum = 0;
 8         int res = 0;
 9         
10         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
11         hm.put(0, -1);
12         
13         for(int i = 0; i<nums.length; i++){
14             sum += nums[i];
15             if(hm.containsKey(sum-k)){
16                 res = Math.max(res, i-hm.get(sum-k));
17             }
18             
19             if(!hm.containsKey(sum)){
20                 hm.put(sum, i);
21             }
22         }
23         return res;
24     }
25 }

类似Minimum Operations to Reduce X to ZeroContiguous ArraySubarray Sum Equals K.

posted @ 2016-03-03 13:28  Dylan_Java_NYC  阅读(418)  评论(0编辑  收藏  举报