300. Longest Increasing Subsequence

DP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int lengthOfLIS(int[] nums) {
int maxLength = 1;

// 定义 dp[i] 为以 nums[i] 结尾的最长严格递增子序列的长度
int[] dp = new int[nums.length];

for (int i = 0; i < nums.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}

maxLength = Math.max(maxLength, dp[i]);
}

return maxLength;
}
}
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
class Solution {
public int lengthOfLIS(int[] nums) {
// 定义 tails[i] 为长度为 i + 1 的子序列的末尾元素的最小值
int[] tails = new int[nums.length];
int nextIndex = 0;

for (int num : nums) {
int insertIndex = findInsertIndex(tails, 0, nextIndex - 1, num);
tails[insertIndex] = num;
if (insertIndex == nextIndex) {
nextIndex++;
}
}

return nextIndex;
}

private int findInsertIndex(int[] nums, int left, int right, int target) {
// 找到大于等于 target 的首个位置
// [1, 3, 5, 7], target = 2, return: 1

while (left <= right) {
int mid = (left + right) >>> 1;
if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}

// now: right, left
return left;
}
}

References

300. Longest Increasing Subsequence