★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-gtljdhrz-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array A
of integers, return true
if and only if it is a valid mountain array.git
Recall that A is a mountain array if and only if:github
A.length >= 3
i
with 0 < 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:spa
Input: [0,3,2,1]
Output: true
Note:code
0 <= A.length <= 10000
0 <= A[i] <= 10000
給定一個整數數組 A
,若是它是有效的山脈數組就返回 true
,不然返回 false
。htm
讓咱們回顧一下,若是 A 知足下述條件,那麼它是一個山脈數組:blog
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:get
輸入:[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 = 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 }