Given an array of integers arr
, return true
if and only if it is a valid mountain array.java
Recall that arr is a mountain array if and only if:數組
arr.length >= 3
i
with 0 < i < arr.length - 1
such that:
arr[0] < arr[1] < ... < arr[i - 1] < A[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Example 1:code
Input: arr = [2,1] Output: false
Example 2:blog
Input: arr = [3,5,5] Output: false
Example 3:it
Input: arr = [0,3,2,1] Output: true
Constraints:io
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^4
判斷數組是否知足前半段單調遞增,後半段單調遞減。class
從前日後找遞增結束點,從後往前找遞增結束點,判斷是否重合且知足峯頂定義。im
class Solution { public boolean validMountainArray(int[] arr) { if (arr.length < 3) { return false; } int left = 1, right = arr.length - 2; while (left < arr.length - 1 && arr[left] > arr[left - 1] && arr[left + 1] > arr[left]) { left++; } while (right > 1 && arr[right] > arr[right + 1] && arr[right - 1] > arr[right]) { right--; } return left == right && arr[left] > arr[left - 1] && arr[left] > arr[left + 1]; } }