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)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84984249