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

Increasing Triplet Subsequence问题及解法

2017-10-18 11:00 609 查看
问题描述:

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.

示例:

Given 
[1, 2, 3, 4, 5]
,

return 
true
.

Given 
[5, 4, 3, 2, 1]
,

return 
false
.

问题分析:

该题与Longest
Increasing Subsequence 分析类似,这里不多赘述。

过程详见代码:

class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < nums.size(); i++)
{
if (res.empty())
{
res.emplace_back(nums[i]);
continue;
}
int size = res.size();
for (int j = 0; j < size; j++)
{
if (nums[i] <= res[j])
{
res[j] = nums[i];
break;
}
}
if (nums[i] > res.back()) res.emplace_back(nums[i]);
if (res.size() >= 3) return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: