题目大意:给你一个0 ~ n-1的排列,问你最多能分成几组,每组分别排序后能够组成0 ~ n-1。
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:
1 2 3 4 5 |
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:
1 2 3 4 5 |
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:
arr
will have length in range[1, 10]
.arr[i]
will be a permutation of[0, 1, ..., arr.length - 1]
.
Solution 1: Max so far / Set
Time complexity: O(nlogn)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua // Running time: 3 ms class Solution { public: int maxChunksToSorted(vector<int>& arr) { int ans = 0; set<int> s; for (int i = 0; i < arr.size(); ++i) { s.insert(arr[i]); if (*s.rbegin() == i) ++ans; } return ans; } }; |
Solution 2: Max so far
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua // Running time: 4 ms class Solution { public: int maxChunksToSorted(vector<int>& arr) { int ans = 0; int m = 0; for (int i = 0; i < arr.size(); ++i) { m = max(m, arr[i]); if (m == i) ++ans; } return ans; } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua // Running time: 5 ms class Solution { public int maxChunksToSorted(int[] arr) { int max = 0; int ans = 0; for (int i = 0; i < arr.length; ++i) { max = Math.max(max, arr[i]); if (max == i) ++ans; } return ans; } } |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 |
""" Author: Huahua Running time: 53 ms """ class Solution: def maxChunksToSorted(self, arr): m = 0 ans = 0 for i, n in enumerate(arr): if n > m: m = n if m == i: ans += 1 return ans |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment