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。

代码如下:

  1. class Solution {
  2. public:
  3. bool increasingTriplet(vector<int>& nums) {
  4. vector<int> dp(nums.size(),1);
  5. for(int i=0;i<nums.size();i++){
  6. for(int j=0;j<i;j++){
  7. if(nums[j]<nums[i]){
  8. dp[i]=max(dp[i],dp[j]+1);
  9. if(dp[i]==3){
  10. return true;
  11. }
  12. }
  13. }
  14. }
  15. return false;
  16. }
  17. };
上述代码不满足题目要求的时间复杂度和空间复杂度。另一种思路是遍历数组,维护一个第一小值min1与第二小值min2,遍历数组,如果nums[i]<=min1,用nums[i]更新min1,否则如果nums[i]<=min2,用nums[i]更新min2,否则只可能nums[i]同时大于min1与min2,那么说明该数组中能找到长度为3的递增子数组,返回true。如果一直没有返回,说明不能找到,直接在最后返回false。
  1. class Solution {
  2. public:
  3. bool increasingTriplet(vector<int>& nums) {
  4. int min1=INT_MAX;
  5. int min2=INT_MAX;
  6. for(auto a:nums){
  7. if(a<=min1)
  8. min1=a;
  9. else if(a<=min2)
  10. min2=a;
  11. else
  12. return true;
  13. }
  14. return false;
  15. }
  16. };


 





posted @ 2016-03-05 22:37  ZHOU YANG  阅读(320)  评论(0)    收藏  举报