博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode & 剑指offer刷题】数组题17:Increasing Triplet Subsequence
阅读量:4560 次
发布时间:2019-06-08

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

Increasing Triplet Subsequence

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
.
Credits:
Special thanks to
 
 
for adding this problem and creating all test cases.

C++
 
/*
判断是否存在增序排列的三元子序列(元素不用连续)
用两个临时变量存储第一个数和第二个数,x当做第三个数
例1:
input = [1 4 2 5 3]
c1,c2初始化为最大值INT_MAX
c1 = 1
c2 = 4 ->  c2 =2  ->  c3 =5 ,return true
例2:
[2 4 1 5]
c1 = 2,
c2 = 4,
c1 = 1,
c3 = 5,return true,
能走到c3说明存在,但是c1,c2, c3存的数并不一定是符合要求的(顺序可能不对)
O(n),O(1)
 
类似问题:
*/
#include <climits>
class
Solution
{
public
:
   
bool
increasingTriplet
(
vector
<
int
>&
a
)
   
{
       
if
(
a
.
size
()<
3
)
return
false
;
       
int
c1
=
INT_MAX
,
c2
=
INT_MAX
;
       
       
for
(
int
x
:
a
)
       
{
           
if
(
x
<=
c1
)
c1
=
x
;
//c1为扫描过程中遇到的最小数,是第一个数的候选
           
else
if
(
x
<=
c2
)
c2
=
x
;
//当x>c1时,x可能为c2或者c3
           
else
return
true
;
//c1<c2<x,说明这样的三元子序列存在
       
}
       
return
false
;
   
}
};
/*错误:没有考虑元素可以不连续
class Solution
{
public:
    bool increasingTriplet(vector<int>& a)
    {
        if(a.size()<3) return false;
       
        for(int i = 0; i<a.size()-2; i++) //从第一个数扫描至倒数第3个元素
        {
            if(a[i]<a[i+1] && a[i+1] < a[i+2]) return true;
        }
        return false;
    }
};*/
 

 

转载于:https://www.cnblogs.com/wikiwen/p/10224404.html

你可能感兴趣的文章
java中类的组合机制
查看>>
git安装及使用
查看>>
mysql一个非常实用解决sql查询优化的函数explain
查看>>
图文讲解NTFS和FAT32硬盘下 asp.net 生成word 错误: 80070005 和 错误:8000401a 的解决方法...
查看>>
《学习》5连接查询(高级查询)
查看>>
arch更新pacman到4.0注意事项
查看>>
python日常—爬取豆瓣250条电影记录
查看>>
11.3NOIP模拟赛
查看>>
1.SDL介绍
查看>>
【重要更新】语言转换类编程工具Tangible系列本月又更新了!
查看>>
现场赛:开关灯问题
查看>>
codeforces A. Jeff and Rounding (数学公式+贪心)
查看>>
zoj 3462
查看>>
java多线程-信号量
查看>>
如何在Delphi XE2中使用Dynamic Web TWAIN
查看>>
js自定义实用函数总结
查看>>
java内存区域与内存溢出异常
查看>>
点点滴滴的成长[2011-11-1]:理解C#修饰符
查看>>
csrf(跨站请求伪造)
查看>>
高性能MySQL笔记-第1章MySQL Architecture and History-001
查看>>