Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

941. 有效的山脉数组 #36

Open
funnycoderstar opened this issue Jan 3, 2019 · 0 comments
Open

941. 有效的山脉数组 #36

funnycoderstar opened this issue Jan 3, 2019 · 0 comments
Labels
Array 数组

Comments

@funnycoderstar
Copy link
Owner

题目描述

给定一个整数数组 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

解题思路

首先解读题目中山脉数组的定义:长度大于3,且先递增后递减的数组。

具体解决思路

  1. 找到数组中最大值所在位置的索引和对应的值
  2. 判断最大值索引是否大于0且小于数组长度-1(处理无法递增或者递减的情况)
  3. 判断数组是否先递增到最大值索引,然后从最大值索引一直递减

代码实现

/**
 * @param {number[]} A
 * @return {boolean}
 */
var validMountainArray = function(A) {
    if(A.length < 3) {
        return false;
    }
    let max = A[0];
    let maxIndex = 0;
    for(let i = 1; i < A.length; i++) {
        let a = A[i];
        if(a > max) {
            max = a;
            maxIndex = i;
        }
    }
    if(maxIndex > 0 && maxIndex < A.length - 1) {
        let isIncrease = true;
        let isDecrease = true;
        for(let i = 0; i < maxIndex; i++) {
            if(A[i] > A[i+1]) {
                isIncrease = false;
                break;
            }
        }
        for(let i = maxIndex; i < A.length - 1; i++) {
            if(A[i] <= A[i+1]) {
                isDecrease = false;
                break;
            }
        }
        return isIncrease && isDecrease;
    } else {
        return false;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Array 数组
Projects
None yet
Development

No branches or pull requests

1 participant