★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-sxqycwvm-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
What is the most number of chunks we could have made?github
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:ui
arr
will have length in range [1, 10]
.arr[i]
will be a permutation of [0, 1, ..., arr.length - 1]
.數組arr
是[0, 1, ..., arr.length - 1]
的一種排列,咱們將這個數組分割成幾個「塊」,並將這些塊分別進行排序。以後再鏈接起來,使得鏈接的結果和按升序排序後的原數組相同。spa
咱們最多能將數組分紅多少塊?code
示例 1:htm
輸入: arr = [4,3,2,1,0] 輸出: 1 解釋: 將數組分紅2塊或者更多塊,都沒法獲得所需的結果。 例如,分紅 [4, 3], [2, 1, 0] 的結果是 [3, 4, 0, 1, 2],這不是有序的數組。
示例 2:blog
輸入: arr = [1,0,2,3,4] 輸出: 4 解釋: 咱們能夠把它分紅兩塊,例如 [1, 0], [2, 3, 4]。 然而,分紅 [1, 0], [2], [3], [4] 能夠獲得最多的塊數。
注意:
arr
的長度在 [1, 10]
之間。arr[i]
是 [0, 1, ..., arr.length - 1]
的一種排列。1 class Solution { 2 func maxChunksToSorted(_ arr: [Int]) -> Int { 3 var res:Int = 0 4 var n:Int = arr.count 5 var mx:Int = 0 6 for i in 0..<n 7 { 8 mx = max(mx, arr[i]) 9 if mx == i 10 { 11 res += 1 12 } 13 } 14 return res 15 } 16 }
18268 kb
1 class Solution { 2 func maxChunksToSorted(_ arr: [Int]) -> Int { 3 let n = arr.count 4 var minOfRight = Array(repeating: 0, count: n) 5 var maxOfLeft = Array(repeating: 0, count: n) 6 7 maxOfLeft[0] = arr[0] 8 minOfRight[n-1] = arr[n-1] 9 10 for i in 1..<n { 11 maxOfLeft[i] = max(maxOfLeft[i-1], arr[i]) 12 } 13 14 for i in (0..<(n - 1)).reversed() { 15 minOfRight[i] = min(minOfRight[i+1], arr[i]) 16 } 17 18 var res = 1 19 20 for i in 1..<n { 21 res += maxOfLeft[i-1] <= minOfRight[i] ? 1 : 0 22 } 23 return res 24 } 25 }
24ms
1 class Solution { 2 func maxChunksToSorted(_ arr: [Int]) -> Int { 3 var result = 0 4 let count = arr.count 5 var left = 0 6 var right = 0 7 8 while left < count { 9 right = arr[left] 10 while left <= right { 11 right = max(right, arr[left]) 12 left += 1 13 } 14 result += 1 15 } 16 return result 17 } 18 }