zoukankan      html  css  js  c++  java
  • LeetCode 941. Valid Mountain Array (有效的山脉数组)

    题目标签:Array

      题目给了一组int array A,让我们判断它是否是 一个山脉数组。

      山脉数组一定要有一个最高值,然后要同时有 山坡和下坡。

      想法是,从左边开始依次比较两个数字,int[0] int[1].... 如果是上坡,继续寻找,如果遇到了下坡,停止,这样就找到了最高点。

      从右边也是同样的操作。

      然后排除只有上坡的,或者只有下坡的情况。

      最后比较一下, 左边找到的最高点和右边找到的最高点是否是同一个点。

      具体看code。

    Java Solution:

    Runtime beats 99.95% 

    完成日期:03/05/2019

    关键点:从左右两个方向各自找最高点

    class Solution 
    {
        public boolean validMountainArray(int[] A) 
        {
            if(A.length < 3)
                return false;
            
            int left = 0;
            int right = A.length - 1;
        
            // from left: climb the hill until the highest reached
            while(left + 1 < A.length && A[left] < A[left + 1])
                left++;
            // from right: climb the hill until the highest reached
            while(right - 1 > 0 && A[right] < A[right - 1])
                right--;
            
            
            if(left == A.length - 1) // only uphill
                return false;
            else if(right == 0) // only downhill
                return false;
            
            
            return left == right;
        }
    }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    ES6笔记
    JavaScriptOOP (三)
    JavaScriptOOP(二)
    JavaScriptOOP(一)
    基于vue-cli 将webpack3 升级到 webpack4 配置
    JavaScript 中 call,apply 和 bind
    vue 2.6 更新变动
    JavaScript严格模式
    vue 修饰符 整理
    webpack打包将配置文件单独抽离不压缩打包
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/10508434.html
Copyright © 2011-2022 走看看