题目:
Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.
What is the most number of chunks we could have made?
Example 1:
Input: arr = [4,3,2,1,0] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
Example 2:
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.
Note:
arrwill have length in range[1, 10].arr[i]will be a permutation of[0, 1, ..., arr.length - 1].
思路:
感觉这道题目和[Leetcode] 768. Max Chunks To Make Sorted II 解题报告完全一样啊!
代码:
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int size = arr.size();
vector<int> right_min(size, 0);
right_min[size - 1] = arr[size - 1];
for (int i = size - 2; i >= 0; --i) {
right_min[i] = min(right_min[i + 1], arr[i]);
}
int ans = 1, left_max = arr[0];
for (int i = 1; i < size; ++i) {
if (right_min[i] < left_max) {
left_max = max(arr[i], left_max);
}
else {
++ans;
left_max = arr[i];
}
}
return ans;
}
};
探讨如何将一个排列数组通过划分并独立排序各部分,再合并后得到完全有序数组的方法。给出两个示例说明,并提供了一个高效的C++解决方案。
392

被折叠的 条评论
为什么被折叠?



