LeetCode 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 <= jA[i] <= A[j].  An array A is monotone decreasing if for all i <= jA[i] >= A[j].

Return true if and only if the given array A is monotonic.

题目分析及思路

定义了一个monotonic数组,要求它要么是单调递增(对所有索引i <= j,对应元素A[i] <= A[j])要么是单调递减(对所有索引i <= j,对应元素A[i] >= A[j])。现在需要判断给定数组是否是monotonic。可以将给定数组与正序排好的数组和逆序排好的数组进行比较,若满足其中一项,则返回True。

python代码 

class Solution:

    def isMonotonic(self, A: List[int]) -> bool:

        return A == sorted(A) or A == sorted(A, reverse=True)

        

 

posted on 2019-03-23 14:35  锋上磬音  阅读(81)  评论(0编辑  收藏  举报