896. Monotonic Array

LeetCode 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 <= 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:

Example 5:

Input: [1,1,1]
Output: true

Note:

  1. 1 <= A.length <= 50000
  2. -100000 <= A[i] <= 100000

解決

該題主要是求給定一個(gè)數(shù)組,判斷該數(shù)組是否是單調(diào)數(shù)組,這里給出兩種解決方案,其中方案二為遞歸方法。

代碼

常規(guī)方案

   /**
   *  常規(guī)方案
   * @param A
   * @return
   */
  public boolean isMonotonic(int[] A) {

      //ascStatus 遞增 默認(rèn)true
      //descStatus 遞減 默認(rèn)true
      boolean ascStatus = true;
      boolean descStatus = true;
      if (A.length == 1||A.length==0) {
          return true;
      }
      //循環(huán)內(nèi)判斷遞增或者遞減
      for (int i = 0; i < A.length - 1; i++) {
          if (A[i] < A[i + 1]) {
              ascStatus = false;
          }
          if (A[i] > A[i + 1]) {
              descStatus = false;
          }
      }
      return (ascStatus||descStatus);
  }

遞歸方案

 /**
   * 遞歸方案
   * @param A
   * @return
   */
  public boolean isMonotonic(int[] A) {
      int len = A.length;
      return isDecrease(A,len)||isIncrease(A,len);
  }
  /**
   * 遞增判斷  遞歸
   * @param A
   * @param len
   * @return
   */
  public boolean isIncrease(int[] A,int len){
      if(len==1){
          return true;
      }
      return (A[len-2]<=A[len-1]&&isIncrease(A,len-1));
  }

  /**
   * 遞減判斷 遞歸
   * @param A
   * @param len
   * @return
   */
  public boolean isDecrease(int[] A,int len){
      if(len==1){
          return true;
      }
      return (A[len-2]>=A[len-1]&&isDecrease(A,len-1));
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 好久不見,是一杯清涼的茶水,需要經(jīng)過漫長的品嘗與回味,才能感受到它沁心的清雅與爽口。 讓我們跟隨花朵朵(楊子珊)與...
    那花評(píng)書閱讀 1,895評(píng)論 6 12
  • 最近這周忙瘋了,基本23點(diǎn)多才關(guān)閉電腦…一堆堆的任務(wù)積壓…下面這個(gè)畫又不知何時(shí)去取回來了
    宮尬閱讀 226評(píng)論 0 1
  • 在這世界上總有那么一個(gè)人,不是你的父母,也不是你的兄弟姐妹,但是在她面前,你可以像在家人面前一樣,毫無壓力毫無顧慮...
    千晴姑娘閱讀 228評(píng)論 0 0

友情鏈接更多精彩內(nèi)容