#未排序数组中累加和为给定值的最长子数组系列问题补2#
未排序数组中累加和为给定值的最长子数组系列问题补2
https://www.nowcoder.com/practice/ab190c44af0141d58037c3f95109d722
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int[] arr = new int[N]; for (int i = 0; i < N; i++) { arr[i] = in.nextInt(); } int len = getLength(arr); System.out.print(len); } private static int getLength(int[] arr) { if (arr == null) { return 0; } int N = arr.length; //key 正数个数与负数个数的差值, value index Map<Integer,Integer> map = new HashMap<>(); map.put(0,-1); int Z = 0,F = 0;//1的个数,0的个数 int res = 0; for (int i = 0; i < N; i++) { Z += arr[i] == 1 ? 1 : 0; F += arr[i] == 0 ? 1 : 0; int cha = Z - F; if (map.containsKey(cha)) { res = Math.max(res, i - map.get(cha)); }else { map.put(cha,i); } } return res; } }