[leetcode] 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.

这道题是判断数组中是否有三个递增的数字,题目难度为Medium。

题目限定了时间和空间复杂度,所以排序就不考虑了。这里用num0表示当前最小的数字,num1表示存在两个递增数字的情况下比num0大的最小数字。这样遍历数组,如果数字比num0小则更新num0,如果数字介于num0和num1之间则更新num1,如果数字比num1大则存在三个递增的数字。之所以要更新num1,是因为存在[4, 5, 1, 2, 3]这样的数组,在遍历到‘2’时,需要将num1从5更新为2,这样遍历到‘3’时即可返回true。具体代码:

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int num0 = INT_MAX, num1 = INT_MAX;
        for(int num:nums) {
            if(num <= num0) 
                num0 = num;
            else if(num <= num1)
                num1 = num;
            else 
                return true;
        }
        return false;
    }
};
判断中用num <= num0和num <= num1是为了避免判断[1, 2, 2]这样的序列时返回true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值