Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is 4
. Note that 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?
1、(n * n)
int lengthOfLIS(int* nums, int numsSize) { int max = 0; //memorize a array if(numsSize == 0) return 0; int *result = malloc(numsSize * sizeof(int)); result[0] = 1; max = 1; //go over the nums for(int i = 1; i < numsSize; i++){ //check forwards int j = i; int fwd_max = 0; for(; j >= 0; j--){ //find one less than this one, and get the max fwd if(nums[j] < nums[i] && fwd_max < result[j]){ fwd_max = result[j]; //if get the max, break; if(fwd_max == max) break; } } result[i] = fwd_max + 1; if(result[i] > max) max = result[i]; } return max; }
2、(nlgn)
int lengthOfLIS(vector<int>& nums) { vector<int> res; for(int i=0; i<nums.size(); i++) { auto it = std::lower_bound(res.begin(), res.end(), nums[i]); if(it==res.end()) res.push_back(nums[i]); else *it = nums[i]; } return res.size(); }
- 维持一个从小到大的数组
- 如果在数组中检测到有比它大的值就用它替换第一个比它大的值