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
這道題讓我們判斷一個數組是否單調,單調數組就是說這個數組的數字要么是遞增的,要么是遞減的,不存在一會兒遞增一會兒遞減的情況,即不會有山峰存在。這里不是嚴格的遞增或遞減,是允許有相同的數字的。那么我們直接將相鄰的兩個數字比較一下即可,使用兩個標識符,inc 和 dec,初始化均為 true,我們開始時假設這個數組既是遞增的又是遞減的,當然這是不可能的,我們會在后面對其進行更新。在遍歷數組的時候,只要發現某個數字大於其身后的數字了,那么 inc 就會賦值為 false,同理,只要某個數字小於其身后的數字了,dec 就會被賦值為 false,所以在既有遞增又有遞減的數組中,inc 和 dec 都會變為 false,而在單調數組中二者之間至少有一個還會保持為 true,參見代碼如下:
解法一:
class Solution {
public:
bool isMonotonic(vector<int>& A) {
bool inc = true, dec = true;
for (int i = 1; i < A.size(); ++i) {
inc &= (A[i - 1] <= A[i]);
dec &= (A[i - 1] >= A[i]);
if (!inc && !dec) return false;
}
return true;
}
};
跟上面的解法思路很像,只不過沒有用 bool 型的,而是用了整型數字來記錄遞增和遞減的個數,若是單調數組,那么最終在 inc 和 dec 中一定會有一個值是等於數組長度的,參見代碼如下:
解法二:
class Solution {
public:
bool isMonotonic(vector<int>& A) {
int inc = 1, dec = 1, n = A.size();
for (int i = 1; i < n; ++i) {
inc += (A[i - 1] <= A[i]);
dec += (A[i - 1] >= A[i]);
}
return (inc == n) || (dec == n);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/896
參考資料:
https://leetcode.com/problems/monotonic-array/
https://leetcode.com/problems/monotonic-array/discuss/165889/C%2B%2BJavaPython-One-Pass-O(N)
https://leetcode.com/problems/monotonic-array/discuss/172578/Java-O(n)-simple-solution
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)