LeetCode 300 longest increasing subsequence

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

this is a really classic dp problem, like LCS.
and we can solve this very easily.

class Solution {
    public int lengthOfLIS(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        //dp[i] represents the LIS containing current nums[i]
        int[] dp = new int[nums.length];
        
        for (int i = 0; i < nums.length; i++) {
            dp[i] = 1;
        }
        int max = Integer.MIN_VALUE;
        
        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            max = Math.max(max, dp[i]);
        }
        return max == Integer.MIN_VALUE? 1: max;
        
        
    }
}

but we need to pay attention on the follow up:
solve this problem in O(NlogN)
this is so hard.
https://cp-algorithms.com/sequences/longest_increasing_subsequence.html

public class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        int len = 0;
        for (int num : nums) {
            int i = Arrays.binarySearch(dp, 0, len, num);
            if (i < 0) { //that means i = -insert position - 1
                i = -(i + 1); //so this i will be the insert position
            }
            dp[i] = num; 
            if (i == len) {
                len++;
            }
        }
        return len;
    }
}
posted @ 2020-11-10 10:55  EvanMeetTheWorld  阅读(15)  评论(0)    收藏  举报