1. 程式人生 > >Leetcode:300. Longest Increasing Subsequence(最大增長序列)

Leetcode: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.

方法1:(利用動態規劃和二分查詢的方式)

package leetcode;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: LongestIncreasingSubsequence
 * @Description: TOTO
 * @date 2018/12/12 21:04
 **/

// 凡是最小最大問題,最先考慮動態規劃
public class LongestIncreasingSubsequence2 {
    @Test
    public void fun() {
        int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
        int length = lengthOfLIS(nums);
        System.out.println(length);
    }

    private 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) {
                i = -(i + 1);
            }
            dp[i] = num;
            if (i + 1 > len) {
                len = i + 1;
            }
        }
        return len;
    }
}

時間複雜度:O(n.logn)

空間複雜度:O(n)