# leetcode - Monotonic Array
Date: 2023-01-23


#### **问题：**

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

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

Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_.

#### **解答:**

单调数组，当数组个数大于2时， 遍历数组， 通过比较当当前值与前一个值的，确定其是递增还是递减， 遍历过程中，如果有变化那么则不满足单调性。

 

```
def isMonotonic(array):
    if len(array) <= 2:
        return True
    direction = array[1] - array[0]
    for i in range(2, len(array)):
        if direction == 0:
            direction = array[i] - array[i-1]
            continue
        if breakDirection(direction , array[i], array[i-1]):
            return False;
    return True;

def breakDirection (direction, val, preval):
    diff =  val - preval 
    if  direction > 0:
        return diff < 0
    else: 
        return diff > 0
```

 

```
def isMonotonic(array):
    isNoDecreasing = True
    isNoCreasing = True
    for i in range(1, len(array)):
        diff = array[i] - array[i-1]
        if diff > 0:
            isNoCreasing = False;
        else:
            isNoDecreasing = False;
    return isNoCreasing or isNoDecreasing
```

 

#### **参考及引用**

https://www.algoexpert.io/questions/monotonic-array

图片from[**康文獻**](https://www.facebook.com/groups/474930279315210/user/100005101534648/?__cft__[0]=AZXOVAAnUFyR73Gn-pO6aqN8nW1HSr1sHVcXBT5WCQt5XQc6qyERCVI0hqOXKX6C5f9uLOACRZtpQicK5BKzr2oNVRMnFtLGYMJr3nevVCUIQawS217-rtTIqBB7GjNCSVx_ymZyv0WGyXCfzcVLky_MDgNqvGirUPn-qjnt6ONzQtW3r6X3pw7nWOPlyS-Q8IE&__tn__=-UC%2CP-R)

