zoukankan      html  css  js  c++  java
  • 941. Valid Mountain Array

    题目描述

    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[A.length - 1]

    解决思路

    从数组的最左侧开始向右扫描,直到找到第一个不满足A[i]<A[i+1]的下标i,那么i就是这个数组的最高点的下标。如果i=0或者不存在这样的i(即整个数组都是单调递增的),那么就返回false。否则从i开始继续向右扫描,判断接下来的的下标j是否都满足 A[j]>A[j+1],若都满足就返回true,否则返回false。

    class Solution {
        public boolean validMountainArray(int[] A) {
            int N = A.length;
            int i = 0;
    
            // 递增扫描
            while (i + 1 < N && A[i] < A[i + 1]) {
                i++;
            }
    
            // 最高点不能是数组的第一个位置或最后一个位置
            if (i == 0 || i == N - 1) {
                return false;
            }
    
            // 递减扫描
            while (i + 1 < N && A[i] > A[i + 1]) {
                i++;
            }
    
            return i == N - 1;
        }
    }
    
    class Solution {
        public boolean validMountainArray(int[] A) {
            int len = A.length;
            if (len < 3) {
                return false;
            }
    
            int pos=1;
            while(pos < len) {
                if (A[pos-1] < A[pos]) {
                    ++pos;
                } else {
                    break;
                }
            }
            
            if (pos == 1 || pos == len) {
                return false;
            }
    
            while (pos < len) {
                if (A[pos-1] > A[pos]) {
                    ++pos;
                } else {
                    return false;
                }
            }
            
            return pos==len;
        }
    }
    
  • 相关阅读:
    BZOJ3779: 重组病毒
    BZOJ3112 [ZJOI2013]防守战线
    BZOJ4011 [HNOI2015]落忆枫音
    BZOJ2726 [SDOI2012]任务安排
    BZOJ1492 [NOI2007]货币兑换
    BZOJ1597 [USACO2008]土地购买
    BZOJ3611 [HEOI2014]大工程
    BZOJ3991 [SDOI2015]寻宝游戏
    BZOJ3675 [APIO2014]序列分割
    BZOJ1010 [HNOI2008]玩具装箱
  • 原文地址:https://www.cnblogs.com/hunter-w/p/13923587.html
Copyright © 2011-2022 走看看