LeetCode 896. Monotonic Array

原题链接在这里:https://leetcode.com/problems/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 <= 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

题解:

Having a direction as d. If it is increasing, d = 1. If it is decreasing, d = -1.

When seeing a increasing, but d = -1, that means there is decreasing before, return false.

Vice Versa.

Time Complexity: O(n). n = A.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public boolean isMonotonic(int[] A) {
 3         if(A == null || A.length == 0){
 4             return true;
 5         }
 6         
 7         int d = 0;
 8         for(int i = 1; i){
 9             if(A[i] > A[i-1]){
10                 if(d < 0){
11                     return false;
12                 }
13                 
14                 d = 1;
15             }else if(A[i] < A[i-1]){
16                 if(d > 0){
17                     return false;
18                 }
19                 
20                 d = -1;
21             }
22         }
23         
24         return true;
25     }
26 }

 

你可能感兴趣的:(LeetCode 896. Monotonic Array)