LeetCode Increasing Triplet Subsequence

334. Increasing Triplet Subsequence334. 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.

Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:

Input: [1,2,3,4,5]
Output: true

Example 2:

Input: [5,4,3,2,1] Output: false

问一个数组中是否有严格递增的三个数存在。
解法:令a是当前最小值,b是比a大的最小值,如果某个nums[i]>b,则a,b,nums[i]构成严格递增的三个数。
因为a,b是最小的递增二元组,如果连这样都没找到递增序列,则不可能有递增三元组了。
完整代码如下,需要注意数组中可能有相同元素,所以第一个if要用<=。

class Solution {
public:
    bool increasingTriplet(vector<int>& nums)
    {
        int a = INT_MAX, b = INT_MAX;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] <= a) {
                // 必须<=
                a = nums[i];
            }
            else if (nums[i] < b) { // <或<=
                b = nums[i];
            }
            if (nums[i] > b) // 必须>
                return true;
        }
        return false;
    }
};

本代码提交AC,用时9MS。
二刷。首先想到了最长上升子序列,求到LIS,如果长度大于等于3的话,则肯定存在上升的3元组。代码如下:

class Solution {
private:
    int lengthOfLIS(vector<int>& nums)
    {
        int n = nums.size();
        if (n < 1)
            return 0;
        vector<int> B = { nums[0] };
        for (int i = 1; i < n; ++i) {
            if (nums[i] > B.back())
                B.push_back(nums[i]);
            else {
                *lower_bound(B.begin(), B.end(), nums[i]) = nums[i];
            }
        }
        return B.size();
    }
public:
    bool increasingTriplet(vector<int>& nums) { return lengthOfLIS(nums) >= 3; }
};

本代码提交AC,用时6MS。

Leave a Reply

Your email address will not be published. Required fields are marked *