Leetcode: Longest Increasing Subsequence
2015-12-19 17:41
357 查看
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given
The longest increasing subsequence is
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
经典的DP入门题目,温习一下。
O(nlogn)解法,记录LIS最大值中的最小可能取值,用二分查找。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
vector<int> maxVals(nums.size(), 0);
maxVals[0] = nums[0];
int lis = 1;
for (int i = 1; i < nums.size(); ++i) {
int low = 0;
int up = lis - 1;
while (low <= up) {
int mid = (low + up) / 2;
if (maxVals[mid] < nums[i]) {
low = mid + 1;
}
else {
up = mid - 1;
}
}
maxVals[low] = nums[i];
if (low >= lis) {
++lis;
}
}
return lis;
}
};
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?
经典的DP入门题目,温习一下。
class Solution { public: int lengthOfLIS(vector<int>& nums) { if (nums.empty()) { return 0; } vector<int> maxLength(nums.size(), 1); for (int i = 1; i < nums.size(); ++i) { for (int j = 0; j < i; ++j) { if (nums[i] > nums[j]) { maxLength[i] = max(maxLength[i], maxLength[j] + 1); } } } return *max_element(maxLength.begin(), maxLength.end()); } };
O(nlogn)解法,记录LIS最大值中的最小可能取值,用二分查找。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
vector<int> maxVals(nums.size(), 0);
maxVals[0] = nums[0];
int lis = 1;
for (int i = 1; i < nums.size(); ++i) {
int low = 0;
int up = lis - 1;
while (low <= up) {
int mid = (low + up) / 2;
if (maxVals[mid] < nums[i]) {
low = mid + 1;
}
else {
up = mid - 1;
}
}
maxVals[low] = nums[i];
if (low >= lis) {
++lis;
}
}
return lis;
}
};
相关文章推荐
- C++二分查找在搜索引擎多文档求交的应用分析
- C语言编程中实现二分查找的简单入门实例
- C#二分查找算法实例分析
- 在MySQL中实现二分查找的详细教程
- Java实现二分查找算法实例分析
- Python二分查找详解
- 简介二分查找算法与相关的Python实现示例
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem