• 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;
        }
    };


  • 相关阅读:
    判断python字典中key是否存在的两种方法
    @SuppressWarnings("unused")注解的作用
    jsp常见的指令总结
    我们怎么获取数据库中的值或者在数据库中添加值那???
    sql语句中的问号是干什么的???
    第四天:servlet的生命周期和一些细节问题
    第三天:Servlet运行原理
    第二天:tomcat体系结构和第一个Servlet
    第一天:tomcat相关知识和浏览器的访问机制
    在用mvn编译java文件时遇到问题
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/13934395.html
Copyright © 2020-2023  润新知