★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝()➤GitHub地址:➤原文地址: ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★Given an array A
of integers, return true
if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
- There exists some
i
with0 < i < A.length - 1
such that:A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[B.length - 1]
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:
0 <= A.length <= 10000
0 <= A[i] <= 10000
给定一个整数数组 A
,如果它是有效的山脉数组就返回 true
,否则返回 false
。
让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:
A.length >= 3
- 在
0 < i < A.length - 1
条件下,存在i
使得:A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[B.length - 1]
示例 1:
输入:[2,1]输出:false
示例 2:
输入:[3,5,5]输出:false
示例 3:
输入:[0,3,2,1]输出:true
提示:
0 <= A.length <= 10000
0 <= A[i] <= 10000
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 = i11 break12 }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 true20 }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-=111 }12 13 return i == j && i > 0 && i < n - 114 }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 += 110 }11 return i == A.count12 }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 = false12 for i in 1..A[i] {18 startedFalling = true19 } else {20 return false21 }22 }23 24 return startedFalling25 }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 = 010 // 0 -> increase ; 1 -> decrease11 12 if A[0] == maxValue {13 return false14 }15 16 for index in 0..= A[index+1]) ||20 (direction == 1 && A[index] <= A[index+1])21 {22 result = false23 break24 }25 }26 27 if direction == 0 {28 return false29 }30 31 return result32 }33 }