题目大意:给你一堆数让你分块,每块独立排序后和整个数组排序的结果相同,问你最多能分为几块。
Problem:
This question is the same as “Max Chunks to Make Sorted” except the integers of the given array are not necessarily distinct, the input array could be up to length 2000
, and the elements could be up to 10**8
.
Given an array arr
of integers (not necessarily distinct), 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:
1 2 3 4 5 |
Input: arr = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. |
Example 2:
1 2 3 4 5 |
Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. |
Note:
arr
will have length in range[1, 2000]
.arr[i]
will be an integer in range[0, 10**8]
.
Idea:
Reduce the problem to 花花酱 769. Max Chunks To Make Sorted by creating a mapping from number to index in the sorted array.
arr = [2, 3, 5, 4, 4]
sorted = [2, 3, 4, 4, 5]
indices = [0, 1, 4, 2, 3]
Solution: Mapping
Time complexity: O(nlogn)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua // Running time: 19 ms class Solution { public: int maxChunksToSorted(vector<int>& arr) { vector<int> v(arr.size()); std::iota(v.begin(), v.end(), 0); std::sort(v.begin(), v.end(), [&arr](const int i1, const int i2){ return arr[i1] == arr[i2] ? (i1 < i2) : arr[i1] < arr[i2]; }); int ans = 0; int m = 0; for (int i = 0; i < v.size(); ++i) { m = max(m, v[i]); if (m == i) ++ans; } return ans; } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 |
""" Author: Huahua Running time: 95 ms """ class Solution: def maxChunksToSorted(self, arr): v = sorted([(n << 32) | i for i, n in enumerate(arr)]) m = 0 ans = 0 for i, n in enumerate(v): m = max(m, n & 0xffffffff) if i == m: ans += 1 return ans |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment