给定一个无序数组arr,其中元素只能是1或0。求arr所有的子数组中0和1个数相等的最长子数组的长度
[要求]
时间复杂度为,空间复杂度为
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] strArr = br.readLine().split(" "); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = Integer.parseInt(strArr[i]); } HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int maxLen = 0, balance = 0; for(int i = 0; i < n; i++){ balance += arr[i] == 1? 1: -1; if(map.containsKey(balance)){ // 0和1达到平衡时就更新长度 maxLen = Math.max(maxLen, i - map.get(balance)); }else{ map.put(balance, i); } } System.out.println(maxLen); } }
import java.util.Scanner; import java.util.HashMap; import java.util.Map; public class Main { public static int getMaxLength(int[] arr) { int len = 0, sum = 0, k = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); for (int i = 0; i < arr.length; i++) { sum += arr[i] == 0 ? -1 : 1; if (map.containsKey(sum - k)) { len = Math.max(len, i - map.get(sum - k)); } if (!map.containsKey(sum)) { map.put(sum, i); } } return len; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i<n; i++){ arr[i] = sc.nextInt(); } System.out.println(getMaxLength(arr)); } }