您的位置:首页 > 产品设计 > UI/UE

<LeetCode OJ> 334. Increasing Triplet Subsequence

2016-06-14 20:20 429 查看
Total Accepted: 16003 Total
Submissions: 46481 Difficulty: Medium

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 @DjangoUnchained for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Show Similar Problems

分析:

最长上升子串的变形,遇到上升子串长度为3即可停止。但是这里限定了复杂度就麻烦了!

动态规划来做(可以AC,但不符合要求):

class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if(nums.size() < 3)
return false;
int maxLen=1;
vector<int> dp(nums.size(),1);
for(int i=1;i<nums.size();i++)  {
for(int j=0;j<i;j++)  {
if(nums[i]>nums[j] && dp[j]+1 > dp[i])  {
dp[i]=dp[j]+1;
if(maxLen < dp[i])
maxLen = dp[i];
if(maxLen == 3)
return true;
}
}
}
return false;
}
};


别人的答案:

完全符合题目要求,

1)从头开始遍历,并用min记录最小值,secondmin记录次最小值

2)当min和secondmin都找到时,只要存在一个新的值大于这两个值,那么就存在递增的三元子串。

3)特别的,例如[1, 2, 0, 4] 在遍历时,min可能会变成0,但是没关系,min和secondmin的最大值仍为secondmin,依然可以用于判断,且之前存在oldmin(先前的min)和secondmin之间的递增序列。

class Solution {
public:
//具有较强技巧性,不好想。没什么意思!
bool increasingTriplet(vector<int>& nums) {
if(nums.size() < 3)
return false;
int min=INT_MAX;
int second=INT_MAX;
for(int i=0;i<nums.size();i++)  {
if(nums[i] <= min)//必须是等号
min=nums[i];//记录最小值
else if(nums[i] <= second)
second=nums[i];//记录次小值
else//说明存在
return true;
}
return false;
}
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51674344

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:/article/3664871.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: