在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array Find the maximum width of a ramp in Example 1: Input: [6,0,8,2,1,5]
Output: 4
Explanation:
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.
Example 2: Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation:
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
Note:
给定一个整数数组 找出 示例 1: 输入:[6,0,8,2,1,5] 输出:4 解释: 最大宽度的坡为 (i, j) = (1, 5): A[1] = 0 且 A[5] = 5. 示例 2: 输入:[9,8,1,0,1,9,4,0,4,1] 输出:7 解释: 最大宽度的坡为 (i, j) = (2, 9): A[2] = 1 且 A[9] = 1. 提示:
440ms 1 class Solution { 2 func maxWidthRamp(_ A: [Int]) -> Int { 3 var val:[Int] = [Int]() 4 var index:[Int] = [Int]() 5 var n:Int = A.count 6 var ans:Int = 0 7 for i in 0..<n 8 { 9 var x:Int = A[i] 10 var left:Int = 0 11 var right:Int = val.count - 1 12 while(left < right) 13 { 14 var mid:Int = (left + right) / 2 15 if val[mid] <= x 16 { 17 right = mid 18 } 19 else 20 { 21 left = mid + 1 22 } 23 } 24 if left <= right && val[left] <= x 25 { 26 ans = max(ans, i - index[left]) 27 } 28 if val.isEmpty || val.last! > x 29 { 30 val.append(x) 31 index.append(i) 32 } 33 } 34 return ans 35 } 36 } 528ms 1 class Solution 2 { 3 4 struct IndexedValue 5 { 6 let index: Int 7 let value: Int 8 9 init( _ index: Int, _ value: Int ) 10 { 11 self.index = index 12 self.value = value 13 } 14 } 15 16 func maxWidthRamp( _ values: [ Int ] ) -> Int 17 { 18 var indexedValues: [ IndexedValue ] = [] 19 for index in ( 0 ..< values.count ) 20 { 21 22 indexedValues.append( IndexedValue( index, values[ index ] ) ) 23 24 } 25 indexedValues.sort( 26 by: 27 { 28 if $0.value == $1.value 29 { 30 return $0.index < $1.index 31 } 32 else 33 { 34 return $0.value <= $1.value 35 } 36 } 37 ) 38 39 var minIndex: Int = indexedValues[ 0 ].index 40 var maxRamp: Int = 0 41 42 for indexedValue in indexedValues 43 { 44 if indexedValue.index < minIndex 45 { 46 minIndex = indexedValue.index 47 } 48 else 49 { 50 let ramp: Int = ( indexedValue.index - minIndex ) 51 maxRamp = max( maxRamp, ramp ) 52 } 53 } 54 55 return maxRamp 56 } 57 } 1252ms 1 class Solution { 2 func maxWidthRamp(_ A: [Int]) -> Int { 3 var numbers: [[Int]] = Array(repeating: [], count: 50001) 4 for (i, a) in A.enumerated() { 5 numbers[a] = numbers[a] + [i] 6 } 7 var res: [Int] = [] 8 for i in (0...50000) { 9 res += numbers[i] 10 } 11 12 var dist = 0 13 var minN = Int.max 14 for i in (0..<res.count) { 15 if res[i] < minN { 16 minN = res[i] 17 } else { 18 dist = max(dist, res[i] - minN) 19 } 20 } 21 22 23 return dist 24 } 25 }
|
请发表评论