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)