中級_4) 遞增的三元子序列

給定一個未排序的數組,判斷這個數組中是否存在長度爲 3 的遞增子序列。

數學表達式如下:

如果存在這樣的 i, j, k, 且滿足 0 ≤ i < j < k ≤ n-1,
使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否則返回 false 。
說明: 要求算法的時間複雜度爲 O(n),空間複雜度爲 O(1) 。

示例 1:

輸入: [1,2,3,4,5]
輸出: true
示例 2:

輸入: [5,4,3,2,1]
輸出: false

// start with two largest values, as soon as we find a number bigger than both, while both have been updated, return true.

  public boolean increasingTriplet(int[] nums) {
     
        int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
        for (int n : nums) {
            if (n <= small) { small = n; }      // update small if n is smaller than both
            else if (n <= big) { big = n; }     // update big only if greater than small but smaller than big
            else return true;                   // return if you find a number bigger than both
        }
        return false;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章