LeeCode334. Increasing Triplet Subsequence

版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/89047628

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

题目:判断是否存在递增的三元组子序列。时间复杂度需在O(n)

思路1:首先想到的是用最长递增子序列方法。如果长度大于等于3,则返回true。

工程代码下载

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int n = nums.size();
        if(n <= 2) return false;
        vector<int> dp(n, 1);
        int max_len = 1;
        for(int i = 0; i < n; ++i){
            for(int j = 0; j < i; ++j){
                if(nums[j] < nums[i]){
                    dp[i] = max(dp[i], dp[j] + 1);
                    if(dp[i] >= 3) return true;
                }
            }
        }
        return false;
    }
};

思路2: 参见https://leetcode.com/problems/increasing-triplet-subsequence/discuss/79004/Concise-Java-solution-with-comments.。用firstsecond来表示上升子序列的两个分界点。初始值设置为最大值,当num <= first, 更新first;当num > firstnum <= second,更新second;当num > firstnum > second,找到了满足条件的三元组,返回true。

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int first = INT_MAX, second = INT_MAX;
        for(auto num : nums){
            if(num <= first) first = num;
            else if(num <= second) second = num;
            else return true;
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/grllery/article/details/89047628
今日推荐