LeetCode-334. Increasing Triplet Subsequence

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-334. Increasing Triplet Subsequence相关的知识,希望对你有一定的参考价值。

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.

 

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.

题目大意是判断所给的数组中是否存在长度为3的递增序列。

最常规的办法应该是两层循环,逐个判断。时间复杂度较高。还有一种比较巧妙的办法,维护两个距离最近的递增序列,如果能找到第三个则返回true。设置一个small,一个big,small<big。如果能找到一个不小于small和big的就返回true。时间复杂度为O(n)

实现代码:

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        if(nums == null || nums.length < 3)
            return false;
        int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
        for(int value : nums) {
            if(value <= small)
                small = value;
            else if(value <= big)
                big = value;
            else
                return true;
        }
        
        return false;
    }
}

 

以上是关于LeetCode-334. Increasing Triplet Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 334. Increasing Triplet Subsequence

LeetCode 334 Increasing Triplet

leetcode-334 Increasing Triplet Subsequence 解题记录

[leetcode] 334. Increasing Triplet Subsequence

leetcode 334. Increasing Triplet Subsequence

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