leetcode – Monotonic Array

问题:

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

An array nums is monotone increasing if for all i <= jnums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= jnums[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康文獻

Comments are closed.