896. Monotonic Array@python
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.
原题:leetcode 896.Monotonic Array
题意:判断一个数组是否是单调的
1.判断单调性:数组值比较
存在三种情况:
(1)A[0] > A[-1]: 单调递减
(2)A[0] < A[-1]: 单调递增
(3)A[0] == A[-1]: 所有值全相等
2.遍历数组,验证数组是否单调递增或者单调递减或者不变
代码如下:
class Solution(object): def isMonotonic(self, A): """ :type A: List[int] :rtype: bool """ n = len(A) i = 0 if A[0] < A[n-1]: # 单调递增 while i < n-1: if A[i] <= A[i+1]: i += 1 else: return False return True elif A[0] > A[n-1]: # 单调递减 while i < n-1: if A[i] >= A[i+1]: i += 1 else: return False return True else: # 不变 while i < n-1: if A[i] == A[i+1]: i += 1 else: return False return True
时间复杂度: O(n)
空间复杂度: O(1)

浙公网安备 33010602011771号