[Leetcode学习-java] Longest Mountain in Array

问题:

难度:Medium

说明:

题目输入一个数组,然后找出数组内 有波峰 的一个区间,称之为山峰,返回最长的一个 波峰,其中平波不算入长度。

问题链接:https://leetcode.com/problems/longest-mountain-in-array/

相关算法:

[Leetcode学习-java]Consecutive Characters(找到最长重复字符子串):https://blog.csdn.net/qq_28033719/article/details/109486014

[Leetcode学习-java]Find All Anagrams in a String(获取所有异序词):https://blog.csdn.net/qq_28033719/article/details/106194878

输入范围:

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

输入案例:

Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.

我的代码:

我也是使用滑动窗口算法,O1空间和On时间复杂度,真的太合适了,没有优化写了一次,蒙对了。

1、区分上坡下坡两个阶段,而且必定是先上坡,后下坡。

2、任何下坡,区间一定会延伸到下一个上坡的起点 + 1 处,所以任何下坡状态都重设 起点

3、平坡重设起点

class Solution {
    public int longestMountain(int[] A) {
        boolean up = false, down = false;
        int begin = 0, end = 1, len = A.length, max = 0;
        for(;end < len;end ++) {
            while(end < len && A[end] < A[end - 1]) {
                end ++;
                down = true;
            }
            if(up && down) {
                max = Math.max(end - begin, max);
            }
            if(down) {
                begin = end - 1;
            }
            if(end < len && A[end] > A[end - 1]) {
                up = true;
                down = false;
            } else {
                begin = end;
                up = down = false;
            }
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/109735732