LeetCode 334 递增的三元子序列

LeetCode 334 递增的三元子序列

在最长升序子序列问题中, 设序列长度为n, 最长升序子序列长度为m

优化前的时间复杂度: \(O(n*m)\)

优化后的时间复杂度: \(O(n\log{m})\)

空间复杂度: \(O(m)\)

m=3时, m为常数

此时, 时间复杂度:\(O(n)\), 空间复杂度:\(O(1)\)

C艹

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        if (nums.size() < 3) return false;
        
        int dp[3];
        memset(dp, 0x7F, sizeof dp);
        
        for (int num : nums) {
            for (int i = 0; i < 3; ++i) {
                if (dp[i] < num) continue;
                if (i == 2) return true;
                dp[i] = num;
                break;
            }
        }
        
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/Simon-X/p/12210828.html