leetcode 334 递增的三元子序列

虽然超时,但还是要贴一下自己的暴力算法。

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

  一个很巧妙的方法,使用两个变量分别存储最小值与中间值,遍历数组的过程中,遇到比small的数,就将small置为该数,遇到大于small并且小于mid的数,就将mid置为该数,遇到比mid大的数,直接成功。这种替换的关键问题在于不管如何替换,比如对small进行了一次替换,前面的序列中必定存在一个比mid小比当前small大的数据与当前mid构成增序列。

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) 
    {
        int n = nums.size();
        if(n<3)
        return false;
        int small = INT_MAX;
        int mid = INT_MAX;
        for(auto num:nums)
        {
            if(num<=small)
            small = num;
            else if(num<=mid)
            mid = num;
            else
            return true;
        }
        return false;
    }
};

  

posted @ 2021-08-17 10:18  zhaohhhh  阅读(50)  评论(0)    收藏  举报