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
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
原文链接:https://leetcode.com/problems/monotonic-array/
判断一个数组是否是不减数组或者不增数组,不增(不减)数组中可以存在连续两个相等的数组(导数大于等于0)。(严格单调递增或者递减是不可以相等的,导数大于0)
只需要一次遍历数组,先判断前两个元素之间的关系,如果是不减则以后的元素之间关系都是不减,不增也是如此。那么就需要记录下之前数组是属于什么不增还是不减,然后与当前的关系进行比较,发现不同的时候就代表破坏了规则,返回false即可。
/*class Solution {
public:
bool isMonotonic(vector<int>& A) {
if(A.size() == 1)
return true;
int i=1;
bool increase=false;
bool decrease=false;
while(i<A.size()) {
if(A[i] > A[i-1]){//递增
if(increase==false&&decrease==true)
return false;
increase = true;
decrease = false;
}else if(A[i] < A[i-1]) {//递减
if(decrease==false&&increase==true)
return false;
decrease = true;
increase = false;
} else {
i++;
continue;
}
i++;
}
return true;
}
};*/
另一种巧妙的写法,
class Solution {
public:
bool isMonotonic(vector<int>& A) {
int sign = 0;//记录上次的变化
int n = A.size();
for (int i = 0; i < n - 1; i++) {
int new_sign;
if (A[i+1] > A[i])
new_sign = 1;
else if (A[i+1] < A[i])
new_sign = -1;
else
new_sign = 0;
if (new_sign != 0 && new_sign == -sign)//如果发生了变化,并且与之前的变化相反则返回false
return false;
if (sign == 0)//如果上一次代表着不变,则更新为这一次的变化
sign = new_sign;
}
return true;
}
};