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.
Solution:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua class Solution { public: bool isMonotonic(vector<int>& A) { bool inc = true; bool dec = true; for (int i = 1; i < A.size(); ++i) { inc &= A[i] >= A[i - 1]; dec &= A[i] <= A[i - 1]; } return inc || dec; } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution { public boolean isMonotonic(int[] A) { boolean inc = true; boolean dec = true; for (int i = 1; i < A.length; ++i) { inc &= A[i] >= A[i - 1]; dec &= A[i] <= A[i - 1]; } return inc || dec; } } |
Python
1 2 3 4 5 6 7 8 9 10 11 |
# Author: Huahua class Solution: def isMonotonic(self, A): inc = True; dec = True; for i in range(1, len(A)): inc = inc and A[i] >= A[i - 1] dec = dec and A[i] <= A[i - 1] return inc or dec; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment