zoukankan      html  css  js  c++  java
  • LeetCode~941.有效的山脉数组

    941.有效的山脉数组

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

    示例:

    输入:[2,1]
    输出:false
    
    输入:[3,5,5]
    输出:false
    
    输入:[0,3,2,1]
    输出:true
    

    提示

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

    个人思路解析

    class Solution {
        public boolean validMountainArray(int[] A) {
            // 根据条件可以淘汰为空或者长度小于3的数组
            if(A != null && A.length >= 3){
                // 定义一个指针变量
                int index = 1;
                
                // 循环判断当前元素是否大于前一位元素(山峰左侧,上坡)
                while (index < A.length && A[index] > A[index-1]){
                    // 符合条件指针后移继续判断
                    index++;
                }
                
                // 判断指针是否到达末位或着前面元素大于当前元素
                if (index >= A.length || index == 1){
                    // 不符合山峰形状,返回false
                    return false;
                }
                
                // 循环判断剩余元素是否小于前一位元素(山峰右侧,下坡)
                while (index < A.length && A[index] < A[index-1]){
                    // 符合条件指针后移继续判断
                    index++;
                }
                
                // 判断是否完成遍历
                if (index == A.length){
                    // 符合山峰形状,返回true
                    return true;
                }
            }
            return false;
        }
    }
    

    提交结果

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/valid-parentheses

  • 相关阅读:
    button label textfield对齐 textview UI样式
    iOS真机测试
    Android学习
    CoreMontion加速计
    一些用xib加载主界面的过程
    英特尔公司
    CISC和RISC
    Terminating app due to uncaught exception 'NSGenericException' 类崩溃文章收集
    UICollectionView 介绍 <转>
    流媒件应用FreeStreamer 学习2
  • 原文地址:https://www.cnblogs.com/unrecognized/p/11550327.html
Copyright © 2011-2022 走看看