769 题意: 一个数组是 0-N-1 的组合, 数组可以被分成多个chunks, 主要chunks 内部排序好了,整个数组就可以排序好。
768:题目: 和768 类似,只是数组是任意的,不是0-N-1的组合。
Input: arr = [1,0,2,3,4] Output: 4 Explanation: We can split into two chunks, such as [1, 0], [2, 3, 4]. However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
分析: 一个数组 拆分成几块 [I] [I+1] [I+2] [..] [...] 只是需要保证 left chunk 比 right chunk 里任意的数都小才行。
769中因为所有数字都是0-N-1的组合,因此分成多个chunk []里面 最大的 max 和都不会超过index. 比如 假设第一个chunk 是 [4,2,1,3,0], 最大的4 都不会大于 index 4.
因此程序可以写成:
for(int i=0; i<n-1; i++){
max = Math.max(i,max); if(i == max) div++; //因为最大的max 不会超过index, 因此index 和max 重合时就可以作为一个chunk 了
}
768中数组是任意的,参考 Soluation 中的方法一 : https://leetcode.com/problems/max-chunks-to-make-sorted-ii/solution/
方法一:
1.先把数组排序好,这是最终的数组成为 expected, 假设原始数组可以分成
[I] [I+1] [I+2] [..] [...]
那么 任意 [I] 和最终expected 中 相同的分块的数字一定相同,位置不同。
假设 expcted = [ 1 1 2 2] 那么 arry 可能是 [1 2 2 1],那么问题转化成 如何判断 两个子数组元素完全一致 但是 位置不同
比较两个子数组 是否一样
arr1: [1 2 1 2]
arr2: [2 2 1 1]
算法: 设置一个map, 在遇到 arr1 时,value+1, 在遇到 arr2 是 value-1.
并且设置一计数器count, 当arr1 某个数为1 时 count ++
当arr1 某个数为0 时 count --
当arr2 某个数为- 1 时 count ++
当arr2 某个数为 0 时 count --
当count ==0 时, 说明arr1 和arr2 完全一样
code 如下:
class Solution {
public int maxChunksToSorted(int[] arr) {
Map<Integer, Integer> count = new HashMap();
int ans = 0, nonzero = 0;
int[] expect = arr.clone();
Arrays.sort(expect);
for (int i = 0; i < arr.length; ++i) {
int x = arr[i], y = expect[i];
count.put(x, count.getOrDefault(x, 0) + 1);
if (count.get(x) == 0) nonzero--;
if (count.get(x) == 1) nonzero++;
count.put(y, count.getOrDefault(y, 0) - 1);
if (count.get(y) == -1) nonzero++;
if (count.get(y) == 0) nonzero--;
if (nonzero == 0) ans++;
}
return ans;
}
}
方法二: 参考 dicussion 里的解法 https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/113462/Java-solution-left-max-and-right-min. 先看code:
class Solution {
public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int[] maxOfLeft = new int[n];
int[] minOfRight = new int[n];
maxOfLeft[0] = arr[0];
for (int i = 1; i < n; i++) {
maxOfLeft[i] = Math.max(maxOfLeft[i-1], arr[i]);
}
minOfRight[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--) {
minOfRight[i] = Math.min(minOfRight[i + 1], arr[i]);
}
int res = 0;
for (int i = 0; i < n - 1; i++) {
if (maxOfLeft[i] <= minOfRight[i + 1]) res++;
}
return res + 1;
}
}
算法如下:
构造两个数组
int[] maxOfLeft = new int[n];
int[] minOfRight = new int[n];
1. 从左到右找到 从0- i 时最大值 并存储
2. 从右到左 找到从 N-1到 i 时最小value 并存储
具体解释:
1 2 3 4 | 5 6 7
[1...4]..
For a increasing straight line , (Max at i) < (Min of I + 1)...
i.e [1..4] max =4 , [5..7] min in 5 ,
So , If Max < Min , then there is no element on the right side , who belongs on the left side as per above observation.
if Max > Min, it means , there is some element on the right side, who belongs on the left, so we CANNOT create a chunk.