334. Increasing Triplet Subsequence

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.

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

Examples:
Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.

思路一:刚开始的想法,用n1,n2分别记录 arr[i] < arr[j] given 0 ≤ i < j ≤ n-1 ;首先找到第一个降序排列的两个数记作n1,n2,如果往后遍历到一个大于n2的数,返回真;如果在n1和n2之间,将n2更新为较小的数,如果遇到比n1还小的数即为poss(possible),意为有可能成为n1的数,当你一旦遇到一个数在poss和n1之间,那么,就用poss和这个数更新n1,n2。

 bool increasingTriplet(vector<int>& nums) {
        int i,n1,n2;
        int n=nums.size();
        if(n<3) return false;
        for( i=0;i<n;i++)
        {
            if(i>0&&nums[i]>nums[i-1])
            {
                n1=nums[i-1];
                n2=nums[i];
                break;
            }
        }
        if(i==n) return false;
        int poss=INT_MAX;
        for(i=i+1;i<n;i++)
        {
            if(nums[i]>n2) return true;
            else
            if(nums[i]>n1&&nums[i]<n2) n2=nums[i];
            else
            if(nums[i]>poss&&nums[i]<=n1)
            {
                n1=poss;
                n2=nums[i];
            }
            if(nums[i]<n1) poss=nums[i];
        }
        return false;
    }
思路二: 转载于此链接
bool increasingTriplet(vector<int>& nums) {
        int small=INT_MAX, big=INT_MAX;//初始时,设置small和big为三个数中的前两个,一旦遇到比这两个都大的,返回true
        for(auto num:nums)
        {
            if(num<=small) small=num;//首先,如果遇到的数<=small,更新
            else if(num<=big) big=num;//比small大,而<=big,更新big
            else return true;//找到了第三个数
        }
        return false;
    }
举个例子,{1,2,-10,3},当遍历到0是,small=0,big=2,虽然相对顺序不对,但一旦3>2,它肯定大于1,这是仍是对。如果遇到大于-10,但<2的数时,可以更新big,此时,big和small的坐标顺序是满足要求的。

看来我刚开始想多了,没想清楚。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值