896. Monotonic Array - Easy

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i <= jA[i] <= A[j].  An array A is monotone decreasing if for all i <= jA[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. 1 <= A.length <= 50000
  2. -100000 <= A[i] <= 100000

 

M1: two pass

一开始试图在one pass判断两种单调状态,但无法处理 {1, 1, 0}这样的情况,必须得two pass分别判断是单调增还是单调减,再把结果取或。需要遍历两次数组,不是最优。

时间:O(N),空间:O(1)

class Solution {
    public boolean isMonotonic(int[] A) {
        return increasing(A) || decreasing(A);
    }
    private boolean increasing(int[] A) {
        for(int i = 0; i + 2 < A.length; i++) {
            if(A[i] <= A[i+1]) {
                if(A[i+1] > A[i+2])
                    return false;
            } else
                return false;
        }
        return true;
    }
    private boolean decreasing(int[] A) {
        for(int i = 0; i + 2 < A.length; i++) {
            if(A[i] >= A[i+1]) {
                if(A[i+1] < A[i+2])
                    return false;
            } else
                return false;
        }
        return true;
    }
}

 

M2: one pass

在M1的基础上,用两个boolean变量表示增还是减。先把两个值都初始化为true。如果有元素递减,increase=false;如果有元素递增,decrease=false。最后返回increase或decrease

时间:O(N),空间:O(1)

class Solution {
    public boolean isMonotonic(int[] A) {
        if(A.length == 1) return true;
        boolean increasing = true;
        boolean decreasing = true;
        for(int i = 0; i + 1 < A.length; i++) {
            if(A[i] < A[i+1])
                decreasing = false;
            if(A[i] > A[i+1])
                increasing = false;
        }
        return increasing || decreasing;
    }
}

 

posted @ 2018-12-02 15:02  fatttcat  阅读(94)  评论(0编辑  收藏  举报