算法:最长上升子序列

题目

给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

题解

动态规划

-w800

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.acemuder.xxx;
public class Main {
public static void main(String[] args) {
int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
System.out.println(new Main().lengthOfLIS(nums));
}
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length <= 0) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = 1;
for (int i = 1; i < nums.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
}
int max = 1;
for (int i = 0; i < dp.length; i++) {
if (dp[i] > max) {
max = dp[i];
}
}
return max;
}
}

贪心 + 二分查找

-w800

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length <= 0) {
return 0;
}
int[] dp = new int[nums.length + 1];
int len = 1;
dp[len] = nums[0];
for (int i = 1; i < nums.length; i++) {
// System.out.println(Arrays.toString(dp));
if (nums[i] > dp[len]) {
len += 1;
dp[len] = nums[i];
} else {
int begin = 1;
int end = len;
int target = nums[i];
while (dp[begin] < target) {
int mid = (begin + end) / 2;
if (dp[mid] >= target) {
end = mid - 1;
} else {
begin = mid + 1;
}
}
if (dp[begin] > nums[i]) {
dp[begin] = nums[i];
}
}
}
return len;
}
}