博客
关于我
334 递增的三元子序列(贪心)
阅读量:371 次
发布时间:2019-03-04

本文共 847 字,大约阅读时间需要 2 分钟。

1. 问题描述:

给定一个未排序的数组,判断这个数组中是否存在长度为 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence

2. 思路分析:

这道题目其实需要找出一个递增的三元子序列即可,所以我们的想法是需要找出到目前为止第一小的数字与第二小的数字,当出现第三小的数字的时候那么说明这个时候出现了一个递增的三元子序列直接返回True即可,这个贪心策略是正确的,因为我们只是求解出当前到当前位置的三元子序列

3. 代码如下:

class Solution:    def increasingTriplet(self, nums: List[int]) -> bool:        # 其实是找出目前第一小的与第二小的数字, 最后假如发现出现了第三小的数字说明成功了        a, b = sys.maxsize, sys.maxsize        for num in nums:            # 第一小的数字            if num <= a:                a = num            # 第二小的数字            elif num <= b:                b = num            else: return True        return False

 

转载地址:http://pvgr.baihongyu.com/

你可能感兴趣的文章
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>