python
复制代码
bool isMonotonic(int* nums, int numsSize) {
if (numsSize <= 1) {
return true;
}
bool isIncreasing = true;
bool isDecreasing = true;
for (int i = 1; i < numsSize; i++) {
if (nums[i] > nums[i - 1]) {
isDecreasing = false;
}
if (nums[i] < nums[i - 1]) {
isIncreasing = false;
}
}
return isIncreasing || isDecreasing;
}
python
复制代码
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
# 初始化标志变量
isIncreasing = True
isDecreasing = True
# 遍历数组
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
isDecreasing = False
if nums[i] < nums[i - 1]:
isIncreasing = False
# 返回结果
return isIncreasing or isDecreasing