算法: 最长递增子序列300. Longest Increasing Subsequence

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 最长递增子序列300. Longest Increasing Subsequence相关的知识,希望对你有一定的参考价值。

300. Longest Increasing Subsequence

Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

Example 1:

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

Constraints:

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

维护尾数组 计算size

找到最佳位置findIndex(int[] tails, int n, int l, int r), 最大不能超过right,也就是size;找到第一个刚好大于left所有的值;

class Solution 
    public int lengthOfLIS(int[] nums) 
        int[] tails = new int[nums.length];
        int size = 0;
        for (int n: nums) 
            int l = 0, r = size;
            l = findIndex(tails, n, l, r);
            tails[l] = n;
            if (l == size) size++;
        
        return size;
    
    
    private int findIndex(int[] tails, int n, int l, int r) 
        while (l < r) 
            int m = l + (r - l) / 2;
            if (tails[m] < n) 
                l = m + 1;
             else 
                r = m;
            
        
        return l;
    

以上是关于算法: 最长递增子序列300. Longest Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 300. Longest Increasing Subsequence 最长递增子序列 (中等)

leetcode300. Longest Increasing Subsequence 最长递增子序列

算法实践--最长递增子序列(Longest Increasing Subsquence)

[leetcode]300. Longest Increasing Subsequence最长递增子序列

Leetocde300. 最长递增子序列(经典DP)

Leetcode 300. Longest Increasing Subsequence