Leetcode 896. Monotonic Array

题目

链接:https://leetcode.com/problems/monotonic-array/

**Level: ** Easy

Discription:

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

Note:

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

代码

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

思考

  • 算法时间复杂度为O(N),空间复杂度为O(1)。
  • 不能用连续三个数的单增单减来判断全局单调性
  • 数组要么单增要么单减,可以先假设单增单减均为真,在遍历中进行选择关闭其中一个,如果两个均关闭则既不单调递增也不单调递减。
    11表示全为相同值,也就是说用两个二进制位表示四种情况。只有00返回false。
原文地址:https://www.cnblogs.com/zuotongbin/p/10214445.html