LeetCode 845. Longest Mountain in Array C++

本文介绍了一种寻找数组中最长'山脉'子数组的方法。'山脉'定义为包含一个最大值,两侧分别递增和递减的部分,且不允许有相等元素。文章详细解释了如何通过一次遍历实现该目标,并保持O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

845. Longest Mountain in Array

Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold:

B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < … B[i-1] < B[i] > B[i+1] > … > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)

Given an array A of integers, return the length of the longest mountain.

Return 0 if there is no mountain.

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.

Note:

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

Follow up:

  • Can you solve it using only one pass?
  • Can you solve it in O(1) space?

Approach

  1. 给你一数组,问你数组中‘mountian’最长是多少,‘mountain’的定义是这一段数组中有一个最大值,以最大值为分界线左边是递增,右边是递减,当中不允许相等的元素,而且长度不小于3。这道题我的想法比较奇特,用到比较多的if-else ,首先做为mountian需要有一个上坡,我一开是我先要找到上坡,记录长度从一开始,如果当中有元素相等,那么重新记录长度从一开始,直至遇到下坡,当到达下坡的时候我就开始不断更新我的maxn(mountian的长度最大值),直至遇到上坡,我又重一开始记录长度,如果当中有元素相等,那么长度归为一,而且等待上坡再开始记录长度,时间复杂度为O(n),空间复杂度为O(1)。12ms

Code

class Solution {
public:
    int longestMountain(vector<int>& A) {
        if (A.size() < 3)return 0;
        bool up = true;
        int maxn = 0, cnt = 1;
        for (int i = 0; i < A.size()-1; i++) {
            if (up) {
                if (A[i] < A[i + 1]) {
                    cnt++;
                }
                else if(A[i]==A[i+1]){
                    cnt = 1;
                }
                else if(cnt>1&&A[i]>A[i+1]){
                    cnt++;
                    maxn = max(cnt, maxn);
                    up = false;
                }
            }
            else {
                if (A[i] > A[i + 1]&&cnt>1) {
                    cnt++;
                    maxn = max(cnt, maxn);
                }
                else if(A[i]==A[i+1]) {
                    cnt = 1;
                }
                else if(A[i]<A[i+1]){
                    cnt = 1;
                    cnt++;
                    up = true;
                }
            }
        }
        return maxn;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值