题目描述:
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.
Example 1:
Input: [1,2,2,3] Output: true
Example 2:
Input: [6,5,4,4] Output: true
Example 3:
Input: [1,3,2] Output: false
Example 4:
Input: [1,2,4,5] Output: true
Example 5:
Input: [1,1,1] Output: true
解题思路:
判断数组是否单调。
(1)采用Python的all()函数,直接暴力做,判断是否全部的A[i] <= A[i + 1]或A[i] >= A[i + 1]。
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if (all(A[i]<=A[i+1] for i in range(len(A)-1))):
return True
elif (all(A[i]>=A[i+1] for i in range(len(A)-1))):
return True
else:
return False
(2)引入两个变量up, down表示由A[i]到A[i+ 1]的增减。遍历数组,若up和down同时大于0,则说明一定不单调。
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
up, down = 0, 0
for i in range(len(A) - 1):
if A[i + 1] > A[i]:
up += 1
if A[i + 1] < A[i]:
down += 1
if up > 0 and down > 0:
return False
return True
(3)维护三个值,历史值,当前值和当前值的下一个值,用一个指针i,his表示历史值,A[i]表示当前值,A[i + 1]表示当前值的下一个值,若his == A[i],则指针继续走,直到找到一个A[i]和his不同,若A[i] == A[i + 1],指针同样继续,直至二者不同,则相当于去除了历史值,当前值,当前值的下一个值之间相同的数字,则可用斜率的方式来判断单调性。
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if len(A) <= 2:
return True
i = 1
his = A[0]
while i < len(A) - 1:
while his == A[i]:
i += 1
if i >= len(A) - 1:
return True
while A[i + 1] == A[i]:
i += 1
if i >= len(A) - 1:
return True
if (A[i + 1] - A[i]) * (A[i] - his) < 0:
return False
his = A[i]
i += 1
return True
本文介绍了一种算法,用于判断一个数组是否为单调递增或单调递减。通过三种不同的方法实现,包括使用Python的all()函数进行直接比较,引入变量记录数组元素的变化趋势,以及维护历史值、当前值和下一个值来判断单调性。
401

被折叠的 条评论
为什么被折叠?



