[leetcode] 334. Increasing Triplet Subsequence

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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.

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

Example 1:

Input: [1,2,3,4,5]
Output: true

Example 2:

Input: [5,4,3,2,1]
Output: false

分析

题目的意思是:给定一个数组,判断是否有长度为3个以上的递增数组存在。

  • 使用两个指针m1和m2,初始化为整型最大值;
  • 我们遍历数组,如果m1大于等于当前数字,则将当前数字赋给m1;
  • 如果m1小于当前数字且m2大于等于当前数字,那么将当前数字赋给m2;
  • 一旦m2被更新了,说明一定会有一个数小于m2,那么我们就成功的组成了一个长度为2的递增子序列,所以我们一旦遍历到比m2还大的数,我们直接返回ture。
  • 如果我们遇到比m1小的数,还是要更新m1,有可能的话也要更新m2为更小的值,毕竟m2的值越小,能组成长度为3的递增序列的可能性越大。

代码

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int m1=INT_MAX;
        int m2=INT_MAX;
        for(auto a:nums){
            if(m1>=a){
                m1=a;
            }else if(m2>=a){
                m2=a;
            }else return true;
        }
        return false;
    }
};

参考文献

[LeetCode] Increasing Triplet Subsequence 递增的三元子序列

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值