首页 > 其他 > 详细

334. Increasing Triplet Subsequence

时间:2017-07-12 14:38:12      阅读:146      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/prmlab/p/7155119.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!