程序员社区

LeetCode-300-最长递增子序列

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)) 吗?

LeetCode-300-最长递增子序列插图
image-20210626151046698

加速子序列列DP求解

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

LeetCode-300-最长递增子序列插图1
image-20210626151701220
LeetCode-300-最长递增子序列插图2
image-20210626152214249
LeetCode-300-最长递增子序列插图3
image-20210626152431331
LeetCode-300-最长递增子序列插图4
image-20210626152625845
LeetCode-300-最长递增子序列插图5
image-20210626152724312
LeetCode-300-最长递增子序列插图6
image-20210626152826654
LeetCode-300-最长递增子序列插图7
image-20210626152931575
LeetCode-300-最长递增子序列插图8
image-20210626153115528

算法流程:

LeetCode-300-最长递增子序列插图9
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

LeetCode-300-最长递增子序列插图10
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;
    }
}
LeetCode-300-最长递增子序列插图11
image-20210626154310122
赞(0) 打赏
未经允许不得转载:IDEA激活码 » LeetCode-300-最长递增子序列

一个分享Java & Python知识的社区