Skip to content

Latest commit

 

History

History
147 lines (111 loc) · 3.09 KB

File metadata and controls

147 lines (111 loc) · 3.09 KB

English Version

题目描述

给定一个整数数组 arr,如果它是有效的山脉数组就返回 true,否则返回 false

让我们回顾一下,如果 arr 满足下述条件,那么它是一个山脉数组:

  • arr.length >= 3
  • 在 0 < i < arr.length - 1 条件下,存在 i 使得:
    • arr[0] < arr[1] < ... arr[i-1] < arr[i]
    • arr[i] > arr[i+1] > ... > arr[arr.length - 1]

 

 

示例 1:

输入:arr = [2,1]
输出:false

示例 2:

输入:arr = [3,5,5]
输出:false

示例 3:

输入:arr = [0,3,2,1]
输出:true

 

提示:

  • 1 <= arr.length <= 104
  • 0 <= arr[i] <= 104

解法

Python3

class Solution:
    def validMountainArray(self, arr: List[int]) -> bool:
        n = len(arr)
        if n < 3:
            return False
        l, r = 0, n - 1
        while l + 1 < n - 1 and arr[l] < arr[l + 1]:
            l += 1
        while r - 1 > 0 and arr[r] < arr[r - 1]:
            r -= 1
        return l == r

Java

class Solution {

    public boolean validMountainArray(int[] arr) {
        int n = arr.length;
        if (n < 3) {
            return false;
        }
        int l = 0, r = n - 1;
        while (l + 1 < n - 1 && arr[l] < arr[l + 1]) {
            ++l;
        }
        while (r - 1 > 0 && arr[r] < arr[r - 1]) {
            --r;
        }
        return l == r;
    }
}

C++

class Solution {
public:
    bool validMountainArray(vector<int>& arr) {
        int n = arr.size();
        if (n < 3) return 0;
        int l = 0, r = n - 1;
        while (l + 1 < n - 1 && arr[l] < arr[l + 1]) ++l;
        while (r - 1 > 0 && arr[r] < arr[r - 1]) --r;
        return l == r;
    }
};

Go

func validMountainArray(arr []int) bool {
	n := len(arr)
	if n < 3 {
		return false
	}
	l, r := 0, n-1
	for l+1 < n-1 && arr[l] < arr[l+1] {
		l++
	}
	for r-1 > 0 && arr[r] < arr[r-1] {
		r--
	}
	return l == r
}

...