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

LeetCode-300-最长递增子序列

作者: 蒋斌文 | 来源:发表于2021-06-26 15:52 被阅读0次

    LeetCode-300-最长递增子序列

    300. 最长递增子序列

    难度中等

    给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。

    子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。

    示例 1:

    输入:nums = [10,9,2,5,3,7,101,18]
    输出:4
    解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
    

    示例 2:

    输入:nums = [0,1,0,3,2,3]
    输出:4
    

    示例 3:

    输入:nums = [7,7,7,7,7,7,7]
    输出:1
    

    提示:

    • 1 <= nums.length <= 2500
    • -104 <= nums[i] <= 104

    进阶:

    • 你可以设计时间复杂度为 O(n2) 的解决方案吗?
    • 你能将算法的时间复杂度降低到 O(n log(n)) 吗?

    image-20210626151046698

    加速子序列列DP求解

    ends[k] 的值代表 长度为 k+1子序列 的尾部元素值

    image-20210626151701220 image-20210626152214249 image-20210626152431331 image-20210626152625845 image-20210626152724312 image-20210626152826654 image-20210626152931575 image-20210626153115528

    算法流程:

    image-20210626154000089

    作者:jyd
    链接:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/zui-chang-shang-sheng-zi-xu-lie-dong-tai-gui-hua-2/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    image-20210626153847915
    // Dynamic programming + Dichotomy.
    class Solution {
        public int lengthOfLIS(int[] nums) {
            int[] tails = new int[nums.length];
            int res = 0;
            for(int num : nums) {
                int i = 0, j = res;
                while(i < j) {
                    int m = (i + j) / 2;
                    if(tails[m] < num) i = m + 1;
                    else j = m;
                }
                tails[i] = num;
                if(res == j) res++;
            }
            return res;
        }
    }
    
    image-20210626154310122

    相关文章

      网友评论

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

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