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
return
Given
return
问题分析:
该题与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;
}
};
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;
}
};
相关文章推荐
- Longest Continuous Increasing Subsequence 问题及解法
- Longest Increasing Subsequence问题及解法
- 334_Increasing_Triplet_Subsequence
- 【LeetCode】Increasing Triplet Subsequence
- [LeetCode]Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence
- 【Leetcode】Increasing Triplet Subsequence
- LeetCode-Increasing Triplet Subsequence
- LeetCode 之 Increasing Triplet Subsequence
- LeetCode[334] Increasing Triplet Subsequence
- Increasing Triplet Subsequence
- 【LeetCode】Increasing Triplet Subsequence(334)
- 334. Increasing Triplet Subsequence**
- 334. Increasing Triplet Subsequence
- Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence 题解
- 334. Increasing Triplet Subsequence
- 最长递增子序列(longest increasing subsequence) 问题详解
- [Leetcode] #334 Increasing Triplet Subsequence
- LeetCode——Increasing Triplet Subsequence