leetcode 896. Monotonic Array(单调数组)

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].

Return true if and only if the given array A is monotonic.

Example 1:

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

Example 5:

Input: [1,1,1]
Output: true

Note:

1 <= A.length <= 50000
-100000 <= A[i] <= 100000

判断一个数组是否是单调数组,单调是指元素为单调上升或单调下降,单调上升指A[i] <= A[ I+1 ], 单调下降指A[i ] >= A[ i+1 ]

思路:
单调只有一个方向,要么上升要么下降,先确定这个方向。
定义变量larger = -1,-1表示还未确定方向,然后一旦遇到A[i] < A[i +1],确定单调上升,larger=0, 这之后遇到A[i] > A[i+1]时表示出现矛盾,返回false
单调下降时同理
A[i] == A[i+1]对两个方向都适用,不做判断。
如果没有矛盾的情况出现,最后返回true

    public boolean isMonotonic(int[] A) {
        int n = A.length;
        if(n <= 2) return true;
        int larger = -1;
        for(int i = 0; i < n-1; i++) {
            if(larger == -1) {
                if(A[i] < A[i+1]) {
                    larger = 0;
                } else if(A[i] > A[i+1]) {
                    larger = 1;
                }
            } else if (larger == 0) {
                if(A[i] > A[i+1]) return false;
            } else {
                if(A[i] < A[i+1]) return false;
            }
        }
        return true;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值