Skip to content

Commit 7108dce

Browse files
committed
solve 300.最长上升子序列
1 parent bb913a3 commit 7108dce

File tree

2 files changed

+120
-0
lines changed

2 files changed

+120
-0
lines changed

zh/300.最长上升子序列.2.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* @lc app=leetcode.cn id=300 lang=java
3+
*
4+
* [300] 最长上升子序列
5+
*
6+
* https://leetcode-cn.com/problems/longest-increasing-subsequence/description/
7+
*
8+
* algorithms
9+
* Medium (44.40%)
10+
* Likes: 818
11+
* Dislikes: 0
12+
* Total Accepted: 114.6K
13+
* Total Submissions: 256.2K
14+
* Testcase Example: '[10,9,2,5,3,7,101,18]'
15+
*
16+
* 给定一个无序的整数数组,找到其中最长上升子序列的长度。
17+
*
18+
* 示例:
19+
*
20+
* 输入: [10,9,2,5,3,7,101,18]
21+
* 输出: 4
22+
* 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
23+
*
24+
* 说明:
25+
*
26+
*
27+
* 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
28+
* 你算法的时间复杂度应该为 O(n^2) 。
29+
*
30+
*
31+
* 进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
32+
*
33+
*/
34+
35+
// @lc code=start
36+
class Solution {
37+
public int lengthOfLIS(int[] nums) {
38+
int[] dp = new int[nums.length];
39+
Arrays.fill(dp, 1);
40+
41+
for (int i = 1; i < nums.length; i++) {
42+
for (int j = 0; j < i; j++) {
43+
if (nums[j] < nums[i]) {
44+
dp[i] = Math.max(dp[i], dp[j] + 1);
45+
}
46+
}
47+
}
48+
49+
int max = 0;
50+
for (int i = 0; i < nums.length; i++) {
51+
max = Math.max(max, dp[i]);
52+
}
53+
54+
return max;
55+
}
56+
}
57+
// @lc code=end
58+

zh/300.最长上升子序列.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* @lc app=leetcode.cn id=300 lang=java
3+
*
4+
* [300] 最长上升子序列
5+
*
6+
* https://leetcode-cn.com/problems/longest-increasing-subsequence/description/
7+
*
8+
* algorithms
9+
* Medium (44.40%)
10+
* Likes: 818
11+
* Dislikes: 0
12+
* Total Accepted: 114.6K
13+
* Total Submissions: 256.2K
14+
* Testcase Example: '[10,9,2,5,3,7,101,18]'
15+
*
16+
* 给定一个无序的整数数组,找到其中最长上升子序列的长度。
17+
*
18+
* 示例:
19+
*
20+
* 输入: [10,9,2,5,3,7,101,18]
21+
* 输出: 4
22+
* 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
23+
*
24+
* 说明:
25+
*
26+
*
27+
* 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
28+
* 你算法的时间复杂度应该为 O(n^2) 。
29+
*
30+
*
31+
* 进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
32+
*
33+
*/
34+
35+
// @lc code=start
36+
class Solution {
37+
public int lengthOfLIS(int[] nums) {
38+
int[] tails = new int[nums.length];
39+
int res = 0;
40+
41+
for (int num : nums) {
42+
int i = 0, j = res;
43+
// 二分查找 tails 数组,找到第一个大于 num 的数字
44+
while (i < j) {
45+
int mid = i + (j - i) / 2;
46+
if (tails[mid] < num) {
47+
i = mid + 1;
48+
} else {
49+
j = mid;
50+
}
51+
}
52+
tails[i] = num;
53+
if (j == res) {
54+
res++;
55+
}
56+
}
57+
58+
return res;
59+
}
60+
}
61+
// @lc code=end
62+

0 commit comments

Comments
 (0)