334. Increasing Triplet Subsequence

Posted Premiumlab

tags:

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

https://leetcode.com/problems/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.

 

 

 

Sol:

 

Start with the maximum numbers for the first and second element. Then:
(1) Find the first smallest number in the 3 subsequence
(2) Find the second one greater than the first element, reset the first one if it‘s smaller

 

 

class Solution(object):
    def increasingTriplet(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        # Time O(n) SpaceO(1)
        
        if len(nums) < 3:
              return False

        first = second = float(inf)
        for n in nums:
            if n <= first:
                first = n
            elif n <= second:
                second = n
            else:
                return True
        return False
            
            

 

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

LeetCode 334. Increasing Triplet Subsequence

334. Increasing Triplet Subsequence

334. Increasing Triplet Subsequence

LeetCode-334. Increasing Triplet Subsequence

334. Increasing Triplet Subsequence

334. Increasing Triplet Subsequence