300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

 

最长递增子序列

 

C++(4ms):二分

 1 class Solution {
 2 public:
 3     int lengthOfLIS(vector<int>& nums) {
 4         vector<int> tails(nums.size() , 0) ;
 5         int len = 0 ;
 6         for(int num : nums){
 7             int index = binarySearch(tails,len,num) ;
 8             tails[index] = num ;
 9             if (index == len){
10                 len++ ;
11             }
12         }
13         return len ;
14     }
15     
16     int binarySearch(vector<int> tails , int len , int num){
17         int left = 0 ;
18         int right = len ;
19         while(left < right){
20             int mid = left + (right - left) / 2 ;
21             if (tails[mid] == num){
22                 return mid ;
23             }else if(tails[mid] < num){
24                 left = mid + 1 ;
25             }else{
26                 right = mid ;
27             }
28         }
29         return left ;
30     }
31 };

 

 

C++(20ms):dp

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

 

posted @ 2019-01-15 10:59  __Meng  阅读(133)  评论(0编辑  收藏  举报