leetcode 896:Monotonic Array

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 <= 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.

即需要对输入数组进行单调性判断,仅当其单调时,最终返回True。


思路:输入数组无论是单调递增还是递减,都返回True,只有既不是递增也不是递减时,返回False。由此联想到用逻辑运算 or进行处理。代码如下:

class Solution():
    def isMonotonic(self,A):
        is_asc = True
        is_decr = True
        for i in range(1,len(A)):
            if A[i] < A[i-1]:
                is_asc = False
            if A[i] > A[i-1]:
                is_decr = False
        
        return is_acs or is_desc

(ZT)
leetcode上面的一行代码版本(一):
具体思路:两两比较数组中元素的大小关系,若单调,则字典长度为1(全为True,或False),
若数组不单调,则字典中True和False均存在,长度为2.

def isMonotonic(A):    
    return len({x < y for x, y in zip(A, A[1:]) if x != y}) <= 1

leetcode上面的一行代码版本(二):
思路:同样是运用or进行输出,不过在比较时用了python内置的sorted函数。

def isMonotonic2(A):    
    return A == sorted(A) or A == sorted(A,reverse=True)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值