300. 最长上升子序列

 1 class Solution 
 2 {
 3 public:
 4     int lengthOfLIS(vector<int>& nums) 
 5     {
 6         if(nums.size() == 0) return 0;
 7         int n = nums.size();
 8         int res = INT_MIN;
 9         vector<int> dp(n,1);
10 
11         for(int i = 0;i < n;i ++)
12         {
13             for(int j = 0;j < i;j ++)
14             {
15                 if(nums[i] > nums[j] && dp[i] < dp[j] + 1) dp[i] = dp[j] + 1;
16             }
17             if(res < dp[i]) res = dp[i];
18         }
19         //for(auto a : dp) cout << a << " ";
20         return res;
21     }
22 };

 

 1 class Solution 
 2 {
 3 public:
 4     int bisearch(vector<int>& nums, int t) //找到第一个大于等于t的数的下标
 5     {
 6         int low = 0;
 7         int high = nums.size() - 1;
 8         while (low < high) 
 9         {
10             int mid = low + (high - low) / 2;
11             if(nums[mid] >= t) high = mid;
12             else low = mid + 1;
13         }
14         return low;
15     }
16     int lengthOfLIS(vector<int>& nums) 
17     {
18         vector<int> res;//维护一个上升子序列数组
19         for (auto a : nums) 
20         {
21             if (res.empty() || res.back() < a) res.push_back(a);
22             int i = bisearch(res, a);//找到第一个大于等于a的数的下标
23             res[i] = a;//把该下标的值修改成a
24         }
25         return res.size();
26     }
27 };

 

posted @ 2020-03-19 12:56  Jinxiaobo0509  阅读(103)  评论(0)    收藏  举报