原题链接在这里: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记录
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 HashMaphm = new HashMap (); 11 hm.put(0, -1); 12 13 for(int i = 0; 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 }
类似Contiguous Array.