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.
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?
首先看清题意是连续子数组,其次是要求时间复杂度为O(n),复杂度为O(n^2)的方法应该都是第一个想到的,这里就不写出来了,来看一下最优解吧:
首先这道题用到的思路和range sum有些类似,用一个sum变量记录数组前i项的和,如果和等于sum,那么长度加一,但此时的长度不一定是题目要求的最长子数组,因此还需要判断当前长度 和 和为sum的前i项减去和为sum-k的前j项的差哪一个长度较大(前提当然是和为sum-k项存在,因此需要一个hashmap进行搜索),还需要注意到一个细节时采用hashmap进行搜索是不能出现重复的sum的,但是实际数组中是可能出现的,这时我们只保留第一次出现该sum时的索引以保证最大长度,这个比较好理解。代码:
public int maxSubArrayLen(int[] nums, int k) { int len=0; int sum=0; Map<Integer,Integer> map=new HashMap<>(); map.put(0,-1); for(int i=0;i<nums.length;i++){ sum+=nums[i]; if(sum==k) len+=1; else if(map.containsKey(sum-k)) len=Math.max(len,i-map.get(sum-k)); if(!map.containsKey(sum)) map.put(sum,i); } return len; }
和为0的索引需要提前put进去,否则当中途出现第一个sum为0的索引时会把该索引put进去,结果显然是不正确的。