1. 程式人生 > >[Swift Weekly Contest 111]LeetCode941. 有效的山脈數組 | Valid Mountain Array

[Swift Weekly Contest 111]LeetCode941. 有效的山脈數組 | Valid Mountain Array

func it is array [1] ... idm 回顧 als ray

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 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:

Input: [0,3,2,1]
Output: true

Note:

  1. 0 <= A.length <= 10000
  2. 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

提示:

  1. 0 <= A.length <= 10000
  2. 0 <= A[i] <= 10000

456ms

 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 }

[Swift Weekly Contest 111]LeetCode941. 有效的山脈數組 | Valid Mountain Array