LeetCode 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:

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

类似Contiguous Array.

上一篇:js判断输入时间是否大于系统时间


下一篇:尝试利用CentOS环境安装LiteSpeed WEB服务环境的过程