An array is monotonic if it is either monotone increasing or monotone decreasing.html
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]
.git
Return true
if and only if the given array A
is monotonic.github
Example 1:數組
Input: [1,2,2,3] Output: true
Example 2:code
Input: [6,5,4,4] Output: true
Example 3:htm
Input: [1,3,2] Output: false
Example 4:blog
Input: [1,2,4,5] Output: true
Example 5:leetcode
Input: [1,1,1] Output: true
Note:get
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