其他分享
首页 > 其他分享> > LeetCode845数组中的最长山脉-----双指针

LeetCode845数组中的最长山脉-----双指针

作者:互联网

题目表述

把符合下列属性的数组 arr 称为 山脉数组 :

给出一个整数数组 arr,返回最长山脉子数组的长度。如果不存在山脉子数组,返回 0 。

进阶:

双指针

1、初始化一个快指针fast和慢指针slow。
2、利用fast指针寻找递增字串,如果递增字串长度为0,则不可能为山脉,令slow = fast,接着从fast在找递增字串。
3、找到山脉上升部分后再接着从fast寻找下降山脉,设置变量down,记录下降山脉的个数,如果down==0,做无下降部分,也不能成为山脉。
4、记录山脉长度,fast - slow,寻找fast - slow过程中的最大值即可

class Solution {
    public int longestMountain(int[] arr) {
        int slow = 0;
        int fast = 1;
        int res = 0;
        while(fast < arr.length){
            while(fast < arr.length && arr[fast] > arr[fast - 1]){
                fast++;
            }
            if(fast == slow + 1){
                slow = fast;
                fast++;
                continue;
            }
            int down = 0;
            while(fast < arr.length && arr[fast] < arr[fast - 1]){
                fast++;
                down++;
            }
            if(down != 0)
                res = Math.max(fast - slow,res);
            
            slow = fast - 1;
        }
        return res;
    }
}

标签:arr,slow,int,fast,length,-----,山脉,LeetCode845,指针
来源: https://www.cnblogs.com/youngerwb/p/16155111.html