Increasing Triplet Subsequence

题目
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.

答案

dp解法(overkill)

class Solution {
    public boolean increasingTriplet(int[] nums) {
        // dp[i] = what is the length of the longest increasing subsequence that ends at i
        int[] dp = new int[nums.length];
        Arrays.fill(dp, 1);

        for(int i = 1; i < nums.length; i++) {
            for(int j = 0; j < i; j++) {
                if(nums[j] < nums[i]) {
                    if(dp[j] + 1 == 3) return true;
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }

            }
        }

        return false;
    }
}

O(n)解法
Iterate from left to right, maintain the minimum and second minimum numbers.
If you can find some number that is greater than the current minimum and the second minimum, there must be an increasing triplet subsequence.

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int first = Integer.MAX_VALUE;
        int second = Integer.MAX_VALUE;
        for(int x : nums) {
            if(x <= first) first = x;
            else if(x <= second) second = x;
            else return true;
        }
        return false;
    }
}

你可能感兴趣的:(Increasing Triplet Subsequence)