300. Longest Increasing Subsequence

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

Example:

Input: [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. 

Note:

  • 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?

Solution

正常DP解法:

T:O(N^2) S:O(N)

  public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        if(nums.length == 0) return 0;
        Arrays.fill(dp, 1);
        int ret = 1;
        for(int i = 1; i < dp.length; i++){
            for(int j = 0; j < i; j++){
                if(nums[i] > nums[j]){
                    dp[i] = Math.max(dp[i], dp[j]+1);
                }
            }
            ret = Math.max(dp[i], ret);
        }
        return ret;
    }

BinarySearch解法:

T:O(NLogN) S:O(N)

class Solution {
    public int lengthOfLIS(int[] nums) {
        //use this array to record the minimum value of subsequence end with.
        //miniEndWithValue[i] : the minmun value of a increasing subsequence (length = i+1) end with
        //ex: miniEndWithValue[0] : the minmun value of a increasing subsequence (length = 1) end with
        //    this value must be the minum value of nums
        //ex: miniEndWithValue[1] : the minmun end with value of a increasing subsequence( length = 2 ) 
        
        int[] miniEndWithValue = new int[nums.length];
        int len = 0;
        for(int num : nums){
            int i = Arrays.binarySearch(miniEndWithValue, 0, len, num);
            if(i < 0) i = -(i+1);
            miniEndWithValue[i] = num;
            if(i == len){
                len++;
            }
        }
        return len;
    }
}

Last updated

Was this helpful?