334. Increasing Triplet Subsequence
Posted ZHOU YANG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了334. 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 @DjangoUnchained for
adding this problem and creating all test cases.
Subscribe to see which companies asked this question
这道题要求一个没有排序的数组中是否有3个数字满足前后递增的关系。最简单的办法是动态规划,设置一个数组dp,dp[i]表示在i位置之前小于或者等于数字nums[i]的数字的个数。我们首先将数组dp的每个元素初始化成1.然后开始遍历数组,对当前的数字nums[i],如果存在nums[j]<nums[i] (j<i),那么更新dp[i]=max(dp[i],dp[j]+1).如果在更新dp[i]之后,dp[i]的值为3了,那么就返回true,否则返回false。
代码如下:
class Solution { public: bool increasingTriplet(vector<int>& nums) { vector<int> dp(nums.size(),1); for(int i=0;i<nums.size();i++){ for(int j=0;j<i;j++){ if(nums[j]<nums[i]){ dp[i]=max(dp[i],dp[j]+1); if(dp[i]==3){ return true; } } } } return false; } };
class Solution { public: bool increasingTriplet(vector<int>& nums) { vector<int> dp(nums.size(),1); for(int i=0;i<nums.size();i++){ for(int j=0;j<i;j++){ if(nums[j]<nums[i]){ dp[i]=max(dp[i],dp[j]+1); if(dp[i]==3){ return true; } } } } return false; } };
以上是关于334. Increasing Triplet Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 334. Increasing Triplet Subsequence
334. Increasing Triplet Subsequence
334. Increasing Triplet Subsequence
LeetCode-334. Increasing Triplet Subsequence