We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent dc15a6c commit 27c77d0Copy full SHA for 27c77d0
solution/0300.Longest Increasing Subsequence/Solution2.cpp
@@ -0,0 +1,31 @@
1
+class Solution {
2
+// dp[i] 表示当前长度为i+1的最大升序左侧子序列的最小末尾值
3
+// 可以知道dp[]一定是递增的,每多加一个元素就可以用折半查找更新dp
4
+public:
5
+ int lengthOfLIS(vector<int>& nums) {
6
+ if (nums.size() == 0)
7
+ return 0 ;
8
+ int dp[nums.size()] = {nums[0], };
9
+ int maxLen = 1 ; // 刚开始找到的最大左侧子串是第一个元素,长度为1
10
+ for (int i = 1; i < nums.size(); ++i)
11
+ {
12
+ int l = 0, r = maxLen ;
13
+ while (l < r)
14
15
+ const int mid = l + (r-l)/2 ;
16
+ if (dp[mid] < nums[i])
17
+ l = mid+1 ;
18
+ else
19
+ r = mid ;
20
+ }
21
+
22
+ // 长度为l+1的最大上升子序列的最小末尾值可以更新为该元素了
23
+ dp[l] = nums[i] ;
24
25
+ // 如果当前元素比dp中所有元素都大,最大长度就可以+1,并以该元素结尾
26
+ if (l == maxLen)
27
+ ++maxLen ;
28
29
+ return maxLen ;
30
31
+};
0 commit comments