941. Valid Mountain Array*

941. Valid Mountain Array*

https://leetcode.com/problems/valid-mountain-array/

题目描述

Given an array A of integers, return true if and only if it is a valid mountain array.

Recall that A is a mountain array if and only if:

  • A.length >= 3
    There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]

Example 1:

Input: [2,1]
Output: false

Example 2:

Input: [3,5,5]
Output: false

Example 3:

Input: [0,3,2,1]
Output: true

Note:

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

C++ 实现 1

我的实现比较复杂, 放在 C++ 实现 2 中进行介绍. 这里的实现来自 LeetCode 的 Submission.

思路是左右开弓, 只要判断最后两个指针是否重合并且不指向数组的两端.

class Solution 
{
public:
    bool validMountainArray(vector<int>& A) 
    {
        if(A.size()<=2)return false;
        int left=0;
        int right=A.size()-1;
            while(left<A.size()-1&&A[left]<A[left+1])
            {
                left++;
            }
            while(right>0&&A[right]<A[right-1])
            {
                right--;
            }
        return left==right&&left!=A.size()-1&&right!=0;
    }
};

C++ 实现 2

beats 86%. 思路是用 isIncreasing 以及 isDecreasing 来标识数组的状态. 数组处于上升阶段就设置 isIncreasing = true, 数组处于下降阶段就设置 isDecreasing = true.

如果:

  • A[i] > A[i - 1], 即此时数组处于上升阶段, 若此时 isDecreasing = true, 说明上升不连续, 返回 false.
  • A[i] < A[i - 1], 即此时数组处于下降阶段, 如果此时 isIncreasing = true, 说明下降不连续, 返回 false.
  • 然而, 还需要考虑的是, 如果是单调序列, 比如单调递减序列那该咋办. 因此引入 count_inc 来记录上升阶段的大小, 如果最后其值为 0, 说明数组没有经历过上升阶段, 无疑是递减序列, 返回 false.

算了, 不分析了, 没有必要记录这种复杂的方法, 不优雅.

class Solution {
public:
    bool validMountainArray(vector<int>& A) {
        if (A.size() < 3) return false;
        bool isIncreasing = false, isDecreasing = false;
        int count_inc = 0, count_dec = 0;
        for (int i = 1; i < A.size(); ++ i) {
            if (A[i] == A[i - 1]) return false;
            if (A[i] > A[i - 1]) {
                if (isDecreasing) return false;
                isIncreasing = true;
                count_inc += 1;
            }
            if (A[i] < A[i - 1]) {
                if (count_inc == 0) return false; // 处理单调递减序列
                if (count_dec == 0) {
                    count_dec ++;
                    isIncreasing = false;
                }
                if (isIncreasing) return false;
                isDecreasing = true;
            }
        }
        if (!isIncreasing && isDecreasing) return true;
        return false; // 介绍上一个 if 的条件, 可以处理单调递增序列
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值