zoukankan      html  css  js  c++  java
  • 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<A.length; 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 }
  • 相关阅读:
    博客园博客备份
    前后端对字段去除首尾空白
    StringEscapeUtils类的转义与反转义方法
    validatebox自定义验证规则以及使用
    mybatis动态sql中的trim标签的使用
    异步IO
    tomcat_下载
    JDK__下载地址
    Eclipse_下载地址
    Linux守护进程
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12014477.html
Copyright © 2011-2022 走看看