在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array Recall that A is a mountain array if and only if:
Example 1: Input: [2,1]
Output: false
Example 2: Input: [3,5,5]
Output: false
Example 3: Input: [0,3,2,1]
Output: true
Note:
给定一个整数数组 让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:
示例 1: 输入:[2,1] 输出:false 示例 2: 输入:[3,5,5] 输出:false 示例 3: 输入:[0,3,2,1] 输出:true 提示:
256ms 1 class Solution { 2 func validMountainArray(_ A: [Int]) -> Bool { 3 var n:Int = A.count 4 if n < 3 {return false} 5 var pre:Int = n - 1 6 for i in 0..<(n - 1) 7 { 8 if A[i] >= A[i + 1] 9 { 10 pre = i 11 break 12 } 13 } 14 if pre == 0 || pre == n-1 {return false} 15 for i in pre..<(n - 1) 16 { 17 if A[i] <= A[i + 1] {return false} 18 } 19 return true 20 } 21 } 256ms 1 class Solution { 2 func validMountainArray(_ A: [Int]) -> Bool { 3 let n = A.count 4 var i = 0 5 var j = n-1 6 while i + 1 < n , A[i] < A[i+1]{ 7 i+=1 8 } 9 while j > 0 , A[j] < A[j-1]{ 10 j-=1 11 } 12 13 return i == j && i > 0 && i < n - 1 14 } 15 } 260ms 1 class Solution { 2 func validMountainArray(_ A: [Int]) -> Bool { 3 var i = 1 4 while i < A.count && A[i] > A[i-1] { 5 i += 1 6 } 7 if i == 1 || i == A.count { return false } 8 while i < A.count && A[i] < A[i-1] { 9 i += 1 10 } 11 return i == A.count 12 } 13 } 264ms 1 class Solution { 2 func validMountainArray(_ A: [Int]) -> Bool { 3 if A.count < 3 { 4 return false 5 } 6 7 if A[0] > A[1] { 8 return false 9 } 10 11 var startedFalling = false 12 for i in 1..<A.count { 13 if A[i-1] < A[i] { 14 if startedFalling { 15 return false 16 } 17 } else if A[i-1] > A[i] { 18 startedFalling = true 19 } else { 20 return false 21 } 22 } 23 24 return startedFalling 25 } 26 } 388ms 1 class Solution { 2 func validMountainArray(_ A: [Int]) -> Bool { 3 if A.count == 0 { 4 return false 5 } 6 7 var maxValue = A.max()! 8 var result = true 9 var direction = 0 10 // 0 -> increase ; 1 -> decrease 11 12 if A[0] == maxValue { 13 return false 14 } 15 16 for index in 0..<A.count-1 { 17 if A[index] == maxValue {direction = 1} 18 19 if (direction == 0 && A[index] >= A[index+1]) || 20 (direction == 1 && A[index] <= A[index+1]) 21 { 22 result = false 23 break 24 } 25 } 26 27 if direction == 0 { 28 return false 29 } 30 31 return result 32 } 33 }
|
请发表评论