给定一个无序数组arr,其中元素可正、可负、可0。求arr所有子数组中正数与负数个数相等的最长子数组的长度。
O(n)
O(n)
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); /* 5 1 -2 1 1 1 2 */ public static void main(String[] args) { int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ int tmp = sc.nextInt(); if(tmp < 0){ tmp = -1; } if(tmp > 0){ tmp = 1; } arr[i] = tmp; } int k = 0; int maxLen = 0; int sum = 0; // 0 位置到 i位置的sum Map<Integer, Integer> sumPosMap = new HashMap<>(32); // sum 第一次出现的 i sumPosMap.put(0, -1); for(int i = 0; i < n; i++){ sum += arr[i]; if(sumPosMap.containsKey(sum-k)){ int firstPos = sumPosMap.get(sum - k); if(i - firstPos > maxLen){ maxLen = i - firstPos; } } if(!sumPosMap.containsKey(sum)){ sumPosMap.put(sum, i); } } System.out.println(maxLen); } }
对于数组:1 2 3 6
, 求k = 5
key | value |
---|---|
1 | 0 |
sum - k = -4
key | value |
---|---|
1 | 0 |
3 | 1 |
sum - k = -2
key | value |
---|---|
1 | 0 |
3 | 1 |
6 | 2 |
sum - k = 1
key | value |
---|---|
1 | 0 |
3 | 1 |
6 | 2 |
9 | 3 |
sum - k = 4
O(n)
O(n^2)
import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); /* 5 1 -2 1 1 1 2 */ public static void main(String[] args) { int n = sc.nextInt(); int[] arr = new int[n]; // sum[j] - sums[i] : 表示区间:[i, j-1] int[] sums = new int[n + 1]; for(int i=0;i<n;i++){ int tmp = sc.nextInt(); if(tmp < 0){ tmp = -1; } if(tmp > 0){ tmp = 1; } arr[i] = tmp; if(i == 0){ sums[i + 1] = arr[i]; }else { sums[i + 1] = sums[i] + arr[i]; } } int k = 0; int ans = 0; for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ int tmp; int len = j - i + 1; if(len <= ans){ continue; } if(j == i){ tmp = arr[i]; }else { tmp = sums[j + 1] - sums[i]; } if(tmp == k){ ans = Math.max(ans, len); } } if(n - i < ans){ break; } } System.out.println(ans); } }