334. Increasing Triplet Subsequence

Question

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 < kn-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.


Code

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        // if (nums == null || nums.length < 3) return false;
        
        // int[] dp = new int[nums.length];
        // dp[0] = 1;
        
        // for (int i = 1; i < dp.length; i++) {
        //     dp[i] = 1;
        //     for (int j = 0; j < i; j++) {
        //         if (nums[j] < nums[i]) {
        //             dp[i] = Math.max(dp[i], dp[j] + 1);
        //         }
        //         if (dp[i] == 3) return true;
        //     }
        // }
        
        // return false;
        int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE;
        
        for (int n: nums) {
            if (n <= min) {
                min = n;
            } else if (n <= secondMin) {
                secondMin = n;
            } else return true;
        }
        
        return false;
    }
}

Solution

一开始想用类似最长递增子序列的dp思路,虽未超时但是时间复杂度不符合要求。

用两个int分别记录最小值和次小值,如果有值比这两个值大,说明存在类似的三元组。

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