您的位置:首页 > 产品设计 > UI/UE

Leetcode Longest Increasing Subsequence

2015-12-05 10:45 507 查看
Leetcode Longest Increasing Subsequence,本算法主要集中了动态规划和二分搜索,算法复杂度为o(n logn),相关代码如下:

#include<iostream>
#include<vector>

/* There is some tricks in this algorithm. I am inspired by others.
* The core philosophy of the algorithm is dynamic and binary search.
* We used the end variable recorde the max length current, and each
* element in the [0..end] can be substitute by others which have the
* some order as the correspond one.
*/
using namespace std;
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
if (len == 0) {
return 0;
}
vector<int> recoder(len, 1);
int end = -1;
int tmp = 0;
for (int i = 0; i < len; i ++) {
// append the element to the end of substitute the correspond
if (end < 0 || nums[i] > nums[end]) {
nums[++ end] = nums[i];
} else if ((tmp = binarySearch(i, nums, end)) < 0) {
nums[- tmp - 1] = nums[i];
}
}
return end + 1;
}
// Binary search, which reture the opposite number of the correspond
// position.
int binarySearch(int pos, vector<int>& nums, int end) {
int num = nums[pos];
int low = 0;
int high = end;
int mid;
while (1) {
if (high - low <= 1) {
if (nums[pos] < nums[low]) {
return - low - 1;
} else if (nums[pos] == nums[low]) {
return low;
} else if (nums[pos] < nums[high]) {
return - high - 1;
} else if (nums[pos] == nums[high]) {
return high;
} else {
return - high - 2;
}
}
mid = (high + low) / 2;
if (nums[mid] == nums[pos]) {
return mid;
} else if (nums[mid] > nums[pos]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
}
};

// Sample input: ./a.out argv1 argv2
int main(int argc, char* argv[]) {
Solution so;
vector<int> nums;
for (int i = 1; i < argc; i ++) {
nums.push_back(atoi(argv[i]));
}
int re = so.lengthOfLIS(nums);
cout<<"result: "<<re<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息