★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝()➤GitHub地址:➤原文地址: ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★Given an array A
of integers, a ramp is a tuple (i, j)
for which i < j
and A[i] <= A[j]
. The width of such a ramp is j - i
.
Find the maximum width of a ramp in A
. If one doesn't exist, return 0.
Example 1:
Input: [6,0,8,2,1,5]Output: 4Explanation: 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: 7Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
Note:
2 <= A.length <= 50000
0 <= A[i] <= 50000
给定一个整数数组 A
,坡是元组 (i, j)
,其中 i < j
且 A[i] <= A[j]
。这样的坡的宽度为 j - i
。
找出 A
中的坡的最大宽度,如果不存在,返回 0 。
示例 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.
提示:
2 <= A.length <= 50000
0 <= A[i] <= 50000
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..x29 {30 val.append(x)31 index.append(i)32 }33 }34 return ans35 }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 = index12 self.value = value13 }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.value29 {30 return $0.index < $1.index31 }32 else33 {34 return $0.value <= $1.value35 }36 } 37 )38 39 var minIndex: Int = indexedValues[ 0 ].index40 var maxRamp: Int = 041 42 for indexedValue in indexedValues43 {44 if indexedValue.index < minIndex45 {46 minIndex = indexedValue.index47 }48 else49 {50 let ramp: Int = ( indexedValue.index - minIndex )51 maxRamp = max( maxRamp, ramp )52 }53 }54 55 return maxRamp56 }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 = 013 var minN = Int.max14 for i in (0..