在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an 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:
数组 我们最多能将数组分成多少块? 示例 1: 输入: arr = [4,3,2,1,0] 输出: 1 解释: 将数组分成2块或者更多块,都无法得到所需的结果。 例如,分成 [4, 3], [2, 1, 0] 的结果是 [3, 4, 0, 1, 2],这不是有序的数组。 示例 2: 输入: arr = [1,0,2,3,4] 输出: 4 解释: 我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。 然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。 注意:
Runtime: 4 ms
Memory Usage: 19.1 MB
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 }
|
请发表评论