requirements
An array is monotone if it is monotonically increasing or monotonically decreasing.
If for all I <= j, A[I] <= A[j], then array A is monotonically increasing. If for all I <= j, A[I]> = A[j], then array A is monotonically decreasing.
Return true if the given array A is monotonic, false otherwise.
Example 1:
Input: [1,2, 3] Output: trueCopy the code
Example 2:
Input: [6,5,4,4] output: trueCopy the code
Example 3:
Input: [1,3,2] output: falseCopy the code
Example 4:
Input: [1,2,4,5] output: trueCopy the code
Example 5:
Input: [1,1,1] output: trueCopy the code
The core code
class Solution:
def isMonotonic(self, nums: List[int]) - >bool:
return nums == sorted(nums) or nums == sorted(nums,reverse=True)
Copy the code
We are sorting the sequence, because there are two kinds of monotone, one is monotonically increasing, the other is monotonically decreasing, so we use or to combine the two cases, and that is the final result.