其他分享
首页 > 其他分享> > 334. Increasing Triplet Subsequence(也可以使用dp动态规划)

334. Increasing Triplet Subsequence(也可以使用dp动态规划)

作者:互联网

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.

Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:

Input: [1,2,3,4,5]
Output: true

Example 2:

Input: [5,4,3,2,1]
Output: false

class Solution {
public: 
    //直接找出这个最长公共子串
    //用一个数组保存最长公共子串,
    //遍历原始数组,若nums[i] 小于最长公共子串数组开头数,则替换
    //若nums[i]大于最长公共子串数组结尾数,则加入数组
    //若nums[i]在最长公共子串数组中间位置,那么找到有序数组中第一个大于nums[i]的数,替换。
    bool increasingTriplet(vector<int>& nums) {
        if(nums.size()<3)
            return false;
        //存放最长递增子序列。
        vector<int> dp;
        dp.push_back(nums[0]);
        for(int i=1;i<nums.size();i++){
           if(nums[i] > dp.back()){
               dp.push_back(nums[i]);
           }else if(nums[i] < dp[0]){
               dp[0] = nums[i];
           }else{
               //二分查找。查找所有大于key的元素中最左的元素。
                int left = 0,right=dp.size()-1,target=nums[i];
                while(left<=right){
                    int mid = left+(right-left)/2;
                    if(dp[mid] < target) left=mid+1;
                    else right=mid-1;
                }
                dp[left]=nums[i];
           }
        }
        return dp.size() >= 3 ? true:false;
    }
};

 

法二:

class Solution {
public:
    //维护更新最小值和次小值。
    bool increasingTriplet(vector<int>& nums) {
        if(nums.size()<3) return false;
        int smallest = INT_MAX;
        int smaller  = INT_MAX;
        for(int i=0;i<nums.size();i++){
            if(nums[i] <= smallest) smallest = nums[i];
            else if(nums[i] <= smaller) smaller = nums[i];
            else return true;
        }
        return false;
    }
};

 



标签:子串,arr,Triplet,nums,334,Subsequence,数组,最长,dp
来源: https://www.cnblogs.com/wsw-seu/p/13934395.html