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 2:

Input: [6,5,4,4]
Output: true
Example 3:

Input: [1,3,2]
Output: false
Example 4:

Input: [1,2,4,5]
Output: true
Example 5:

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

思路

这个题目很简单,只要数组全部是递增的,或者是递减的(不是严格意义上的递增递减,即,可以允许等于存在),就是true。我们设俩标志位,检查是否满足递增递减就好。

代码

class Solution {
public:
    bool isMonotonic(vector<int>& A) {
        bool creasing = true;
        bool decreasing = true;
        for(int i = 0; i < A.size()-1; i++)
        {
            if(A[i]>A[i+1])
                creasing = false;
            if(A[i]<A[i+1])
                decreasing = false;
        }
        
        return creasing || decreasing;
        
    }
};

    原文作者:美不胜收oo
    原文地址: https://www.jianshu.com/p/0befd1f074ed
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞