LeetCode | 334. Increasing Triplet Subsequence 数学技巧题解析与证明

Givenan unsorted array return whether an increasing subsequence of length 3 existsor not in the array.

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

Youralgorithm should run in O(n) time complexity and O(1) spacecomplexity.

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

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

Credits:
Special thanks to
 @DjangoUnchained foradding this problem and creating all test cases.

这题要求在线性的时间内使用常数空间求出某个数组是否有连续的长度大于等于3的递增子串,

设数组为b1,b2,…bn,设定两个数a,b,遍历数组,当a为空的时候,a=bi,当a不为空的时候,当bi>a的时候而b为空的时候b=bi,b不为空的时候如果bi>b,则说明已经发现了递增子串,返回true,如果b<=bi,假如之后有一个数bk和a,b,构成了三连递增子串,那么,a,bi,bk也必定构成三连递增子串,所以只需要检查a,bi和之后的数是否构成递归子串就好了,这里b=bi,

当a不为空bi<=a的时候,假如a,bk,bp构成了三连递增子串,那么bi,bk,bp也一定构成三连递增子串,只需检查bi和之后的数是否构成递增子串就好了,这里a=bi

以后记得当输入数据为int的时候,可以把min初始化为INT_MAX,或者把max初始化为-INT_MIN

class Solution {

public:

    boolincreasingTriplet(vector<int>& nums) {

      int a = 0, b = 0; int aNull=true,bNull=true;

      for (auto u : nums)

      {

            if (aNull)

            {

                  aNull = false;

                  a = u;

            }

            else

            {

                  if (u > a)

                  {

                       if (bNull)

                       {

                             b = u; bNull=false;

                       }

                       else

                       {

                             if (u > b)

                             {

                                   return true;

                             }

                             else

                             {

                                   b = u;

                             }

                       }

                  }

                  else

                  {

                       a = u;

                  }

            }

      }

      return false;

}

};


 简单版本:

class Solution {

public:

   boolincreasingTriplet(vector<int>& nums) {

      int a = INT_MAX, b = INT_MAX;

      for (auto u : nums)

      {

            if (u <= a) a = u;

            else

            {

                  if (u <= b) b = u;

                  else

                  {

                       return true;

                  }

            }

      }

      return false;

}

};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值