# 896.monotonic array

**896.Monotonic Array**

> 如果数组是单调递增或单调递减的，那么它是单调的。 如果对于所有 i <= j，A\[i] <= A\[j]，那么数组 A 是单调递增的。 如果对于所有 i <= j，A\[i]> = A\[j]，那么数组 A 是单调递减的。 当给定的数组 A 是单调数组时返回 true，否则返回 false。

```
示例 1：

输入：[1,2,2,3]
输出：true
示例 2：

输入：[6,5,4,4]
输出：true
示例 3：

输入：[1,3,2]
输出：false
示例 4：

输入：[1,2,4,5]
输出：true
示例 5：

输入：[1,1,1]
输出：true


提示：

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

方法： 题目比较简单，唯一的难点在于如何改进时间。最初想法如下，先从第一个开始判断，如果大于的往后判断，碰到小于的就返回false。小于也是一样，等于的话删掉第一个元素，递归调用。

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

           }
};
```

更短时间的例子如下，通过两个计数器遍历一遍向量即可。

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/896.monotonic_array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
