zoukankan      html  css  js  c++  java
  • 递增三元子序列

    给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。

    数学表达式如下:

    如果存在这样的 i, j, k,  且满足 0 ≤ i < j < k ≤ n-1,
    使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false

    说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。

    示例 1:

    输入: [1,2,3,4,5]
    输出: true

    示例 2:

    输入: [5,4,3,2,1]
    输出: false

    解题思路

    从前向后遍历数组,使用两个变量分别存储当前为止所观察到的最小值和次小值,当存在第三个值大于次小值时,返回True,否则返回Flase。

    Python3代码如下:

    class Solution:
        def increasingTriplet(self, nums) -> bool:
            if len(nums) < 3 or nums is None:
                return False
            first = float('inf')
            second = float('inf')
            for num in nums:
                if num <= first:
                    first = num
                elif num <= second:
                    second = num
                else:
                    return True
            return False
    
    
    if __name__ == '__main__':
        so = Solution()
        arr = [5, 1, 5, 5, 2, 5, 4]
        print(so.increasingTriplet(arr))
  • 相关阅读:
    [atAGC049E]Increment Decrement
    [atARC099F]Eating Symbols Hard
    [atARC099E]Independence
    [Codeforces] Codeforces Round #456
    Treap
    Splay树
    [Offer收割]编程练习赛42
    [Codeforces]Good Bye 2017
    Codeforces Round #455
    Educational Codeforces Round 35
  • 原文地址:https://www.cnblogs.com/viviane/p/11268596.html
Copyright © 2011-2022 走看看