896、Monotonic Array
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
题目:
如果数组单调递增或单调递减,则数组是单调的。
如果对于所有i <= j,A [i] <= A [j],则数组A是单调递增的。 如果对于所有i <= j,A [i]> = A [j],则数组A是单调递减的。
当且仅当给定的数组A是单调的时,才返回true。
例1:
输入:[1,2,2,3]
输出:true
例2:
输入:[6,5,4,4]
输出:true
例3:
输入:[1,3,2]
输出:false
例4:
输入:[1,2,4,5]
输出:true
例5:
输入:[1,1,1]
输出:true
解法一:
//思路:先判断升序还降序,然后再逐个元素比较,如果不满足条件就跳出。
bool isMonotonic(int* A, int ASize) {
int index=A[0];
int flag;
if(A[0]<=A[ASize-1]){
for(int i=1;i<ASize;i++){
if(A[i]>=index){
index = A[i];
flag=1;
}
else{
flag=0;
break;
}
}
}
else{
for(int j=1;j<ASize;j++){
if(A[j]<=index){
index = A[j];
flag=1;
}
else{
flag=0;
break;
}
}
}
if(flag==1){
return true;
}
else
return false;
}
Runtime: 24 ms
因篇幅问题不能全部显示,请点此查看更多更全内容