题目
未排序数组中累加和为给定值的最长子数组系列问题
java代码
package com.lizhouwei.chapter8;import java.util.HashMap;import java.util.Map;/** * @Description: * @Author: lizhouwei * @CreateDate: 2018/5/7 21:57 * @Modify by: * @ModifyDate:*/public class Chapter8_11 { public int getMaxLength(int[] arr, int k) { if (arr == null) { return 0; } Map map = new HashMap<>(); map.put(0, -1); int sum = 0; int maxLen = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; if (map.containsKey(sum - k)) { maxLen = Math.max(maxLen, i - map.get(sum - k)); } map.put(sum, i); } return maxLen; } //测试 public static void main(String[] args) { Chapter8_11 chapter = new Chapter8_11(); int[] arr = {1, 2, 1, 1, 1}; System.out.print("数组 arr = {1, 2, 1, 1, 1}中和为3的最长子数组长度为:"); int maxLen= chapter.getMaxLength(arr, 3); System.out.print(maxLen); }}
结果