[LeetCode] Increasing Triplet Subsequence

425 查看

Problem

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples

Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.

Note

题目不要求连续的三个增长数,所以只需要更新其中较小的两个数,并在第三个数满足条件的情况下返回true即可。
怎么更新较小的两个数呢,先判断新数是否最小的数,如果是便更新,如果不是,再判断是否第二小的数,如果是便更新,如果不是,那么一定是最大的数,则符合题意,返回TRUE。

Solution

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        int left = Integer.MAX_VALUE, mid = Integer.MAX_VALUE;
        for (int num: nums) {
            if (num <= left) left = num;
            else if (num <= mid) mid = num;
            else return true;
        }
        return false;
    }
}