前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 300. Longest Increasing Subsequence

leetcode 300. Longest Increasing Subsequence

作者头像
眯眯眼的猫头鹰
发布2018-10-31 11:20:20
4100
发布2018-10-31 11:20:20
举报
文章被收录于专栏:眯眯眼猫头鹰的小树杈

题目要求

代码语言:javascript
复制
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?

找到整数数组中最长的递增子数组。该子数组可以为不连续的。如题目中例子所示,[10, 9, 2, 5, 3, 7, 101, 18]得到的最长子数组为[2,3,7,101]

思路一:动态规划

从动态规划的角度来说,假设要计算以第i位为结尾所构成的最长递增子数组,并且我们已经知道了第0位,第1位...第i-1位的任何一个值为最后一个数字时所能构成的最长子数组的长度。那么我们只需要从中找到值比当前小的值的下标,并且比较二者构成的子数组的长度,再从中获得最大长度的递增子数组,作为当前数组为最后一个值所构成的递增子数组的最大长度。

最后我们还需要遍历一遍全部子数组的长度并获得最大的长度。

代码语言:javascript
复制
   public int lengthOfLIS(int[] nums) {
        int length = nums.length;
        if(length==0) return 0;
        int T[] = new int[nums.length];
        for(int i = 1 ; i<length ; i++){
            for(int j = i-1 ; j>=0 ; j-- ){
                if(nums[j] < nums[i] && T[j] + 1 > T[i]){
                    T[i] = T[j] + 1;
                }
            }
        }
        int max = 0;
        for(int cur : T){
            max = Math.max(cur, max);
        }
        return max+1;
    }

思路二:大牛思路

这里附上一个解释的非常好的文章,我根据其思路的实现如下:

代码语言:javascript
复制
    public int lengthOfLIS2(int[] nums){
        int length = nums.length;
        if(length == 0) return 0;
        
        int[] tmp = new int[length];
        tmp[0] = nums[0];
        int max = 1;
        for(int i = 1 ; i<length ; i++){
            for(int j = max-1; j>=0 ; j--){
                if(j==0 && nums[i] < tmp[j]) tmp[j] = nums[i];
                else if(j == max-1 && nums[i] > tmp[j]){
                    tmp[j+1] = nums[i];
                    max++;
                    break;
                }
                else if(nums[i] < tmp[j] && nums[i] >tmp[j-1]){
                    tmp[j] = nums[i];
                    break;
                } 
            }
        }
        return max;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路一:动态规划
  • 思路二:大牛思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档