publicintmaxSubArrayLen(int[] nums,int k) {if (nums ==null||nums.length==0) {return0; }int n =nums.length;int maxLen =0;int[] preSum =newint[n +1];for (int i =1; i <= n; i++) { preSum[i] = nums[i -1] + preSum[i -1]; }// <preSum we need to find, first location that need this preSum>HashMap<Integer,Integer> hm =newHashMap<>();for (int i =0; i <= n; i++) {if (hm.containsKey(preSum[i])) { maxLen =Math.max(maxLen, i -hm.get(preSum[i])); } if (!hm.containsKey(preSum[i] + k)) {// 如果发现不存在的话,每次都要更新一下hmhm.put(preSum[i] + k, i); } }return maxLen;}
publicintmaxSubArrayLen(int[] nums,int k) {if (nums ==null||nums.length==0) {return0; }int n =nums.length;int maxLen =0;int[] preSum =newint[n +1];for (int i =1; i <= n; i++) { preSum[i] = nums[i -1] + preSum[i -1]; }// <preSum we need to find, locations that need this preSum>HashMap<Integer,List<Integer>> hm =newHashMap<>();for (int i =0; i <= n; i++) {if (hm.containsKey(preSum[i])) {List<Integer> tmp =hm.get(preSum[i]);for (Integer elem : tmp) { maxLen =Math.max(maxLen, i - elem); } }List<Integer> tmp;if (hm.containsKey(preSum[i] + k)) { tmp =hm.get(preSum[i] + k); } else { tmp =newArrayList<>(); }tmp.add(i);hm.put(preSum[i] + k, tmp); }return maxLen;}
discuss的clean solution:
publicintmaxSubArrayLen(int[] nums,int k) {int sum =0, max =0;HashMap<Integer,Integer> map =newHashMap<Integer,Integer>();for (int i =0; i <nums.length; i++) { sum = sum + nums[i];if (sum == k) max = i +1;elseif (map.containsKey(sum - k)) max =Math.max(max, i -map.get(sum - k));if (!map.containsKey(sum)) map.put(sum, i); }return max;}