How to determine if a sequence is bitonic?

后端 未结 5 1121
遥遥无期
遥遥无期 2020-12-23 18:00

A sequence is bitonic if it monotonically increases and then monotonically de- creases, or if it can be circularly shifted to monotonically increase and

5条回答
  •  再見小時候
    2020-12-23 18:29

    Here is an efficient and simple implementation in Java. It traverses the array only once to determine whether the array is bitonic or not. It uses a variable reversal that counts the number of direction reversals of monotonicity in the array (including the circular wrapping around).

    The variable trend can have three values:

    • 0, if the values are the same;
    • 1, if the array is monotonically increasing;
    • -1, if the array is monotonically decreasing.
    public static boolean bitonic(int[] arr) {
      int reversal = 0;
      int len = arr.length;
      int trend = 0; // 0 means any, 1 means increasing, -1 means decreasing 
      for (int i= 0; i < len ; i++) {
        if(arr[i%len] < arr[(i+1)%len]){
          if (trend == 0) trend = 1;
          else if ( trend == -1) {
            reversal ++;
            trend = 1;
          }
        }
        else if(arr[i%len] > arr[(i+1)%len]){
          if (trend == 0) trend = -1;
          else if ( trend == 1) {
            reversal ++;
            trend = -1;
          }
        }
        if(reversal > 2) return false;
      }
      return true;
    }
    

提交回复
热议问题