美文网首页
最长递增子序列

最长递增子序列

作者: mrjunwang | 来源:发表于2018-09-26 10:45 被阅读0次

//Given an unsorted array of integers, find the length of longest increasing subsequence.

//For example,
//Given [10, 9, 2, 5, 3, 7, 101, 18],
//The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

//Your algorithm should run in O(n2) complexity.

//Follow up: Could you improve it to O(n log n) time complexity?
1.给出O(n2)的时间复杂度算法

 public int lengthOfLIS(int[] nums) {
            int dp[]=new int[nums.length];
            dp[0]=1;
            int max=1;
            for(int i=1;i<dp.length;i++){
                int maxValue=0;
                for(int j=0;j<i;j++){
                    if(nums[i]>nums[j]){
                        maxValue=Math.max(maxValue, dp[j]);

                    }
                }
                dp[i]=maxValue+1;
                max=Math.max(max, dp[i]);
                
            }
            return max;
        }

2.用二分查找给出O(nlogn)算法


image.png
 public int longestSequence(int[] a){
         int[] sub=new int[a.length];
         int length=0;
         for(int ele:a){
             int index=binarySearch(sub,ele,length);
             sub[index]=ele;
             if(index==length){
                 length++;
             }
                     
         }

         return length;
                 
     }
     
    private int binarySearch(int[] sub, int data, int length) {
        int l=0;
        int r=length;
        while(l<r){
            int mid=l+(r-l)/2;
            if(sub[mid]==data){
                return mid;
            }
            else if(sub[mid]>data){
                r=mid;
            }
            
            else{
                l=mid+1;
            }
        }
        return l;
    }

相关文章

  • LeetCode-300-最长递增子序列

    LeetCode-300-最长递增子序列 300. 最长递增子序列[https://leetcode-cn.com...

  • 动态规划-LIS

    LIS 最长递增子序列 如 x 的 最长递增子序列长度为5 方法一 对 x 排序(升序)生成 x_sorted 对...

  • LeetCode 300. Longest Increasing

    问题描述 给定一个未排序的整数数组,找出最长的递增子序列。 栗子: 注意: 可能存在多种最长递增子序列的组合,只需...

  • 最长递增子序列

    问题描述 求最长递增子序列的长度 分析 主要是确定状态,F[i]表示以ai 结束的最长递增子序列长度,F[i]=m...

  • 经典DP问题合集

    一、上台阶问题 二、矩阵最小路径和 三、最长递增子序列 四、最长公共子序列 五、背包问题

  • 动态规划常见面试题

    子序列类型编辑距离 最长递增子序列 最大子数组 最长公共子序列 背包问题0-1背包问题 子集背包问题 完全背包问题...

  • 最长递增子序列: 动态规划和LCS(最长公共子序列)

    最长递增子序列: 动态规划和LCS(最长公共子序列)子序列和子串的区别:子序列不连续,字串连续。这个题两种解法 动...

  • 最长递增子序列

    //Given an unsorted array of integers, find the length of...

  • 最长递增子序列

    通常有4个步骤来设计动态规划算法: 1.刻画一个最优解的结构特征。 2.递归地定义最优解的值。 3.计算最优解的值...

  • 最长递增子序列

    问题定义: 给定一个长度为N的数组,找出一个最长的单调自增子序列(不一定连续,但是顺序不能乱)。例如:给定一个长度...

网友评论

      本文标题:最长递增子序列

      本文链接:https://www.haomeiwen.com/subject/ljrdoftx.html