Leetcode Increasing Triplet Subsequence

Leetcode Increasing Triplet Subsequence,本题主要的难点是如何使用o(n)的方法进行判别。
我们可以这样考虑,在扫描的时候提供一个下界(low)和上界(high),他们的初始值都不存在,并且在扫描时进行更新,更新方法如下:

  1. 当设置上界后,如果找到大于上界的元素时,此时表示数组中存在满足条件的序列。
  2. 当找到形式nums[i] > nums[i - 1]的元素时,可以推断出如果上界存在时,一定有nums[i] < nums[high],当上界不存在时,此时直接更新。而这一组值做为新的上界与下界,效果与未更新时相同,且包涵了新的更大的范围。
  3. 如果不满足以上情况,在nums[i]在上界与下界的范之中时,我们更新上界,扩大范围。

相关cpp代码如下:

#include<iostream>
#include<vector>

using namespace std;
class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        if (nums.size() < 3) {
            return false;
        }
        int low = 0;
        int high = -1;
        for (int i = 1; i < nums.size(); i++) {
            // if there is a element great than the high bound value
            if (high != -1 && nums[i] > nums[high]) {
                return true;
            }

            // update the lower bound and higher bound
            if (nums[i] > nums[i - 1]) {
                low = nums[i - 1] < nums[low]? i - 1 : low;
                high = i;
            } else if (high != -1 && nums[i] < nums[high] && nums[i] > nums[low]) {
                // update the higher bound
                high = i;
            }
        }
        return false;
    }
};

int main(int argc, char* argv[]) {
    Solution so;
    vector<int> test;
    for (int i = 1; i < argc; i++) {
        test.push_back(atoi(argv[i]));
    }
    cout<<"resutl: "<<so.increasingTriplet(test)<<endl;
    return 0;
}
测试:./a.out 2 1 5 0 3 4
result: 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值