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 is4
.
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)