力扣第300题 最长上升子序列
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int size = nums.size();
if (size == 0)
{
return 0;
}
vector<int> vec;
int len = 1;
vec.push_back(nums[0]);
for (int i = 1; i < size; i++)
{
if (vec[len - 1] < nums[i])
{
vec.push_back(nums[i]);
len++;
}
else
{
// 要替换掉在vec数组中第一个大于nums[i]的数, 此处边界问题需要考虑一下
// right = len - 2是因为vec[len - 1] >= nums[i]所以不用考虑len - 1
int left = 0, right = len - 2, pos = -1;
while (left <= right)
{
int mid = left + ((right - left) >> 1);
if (vec[mid] < nums[i])
{
pos = mid;
left = mid + 1;
}
else
{
right = mid - 1;
}
}
vec[pos + 1] = nums[i];
}
}
return len;
}
};
原文地址:https://www.cnblogs.com/woodjay/p/12495141.html
时间: 2024-11-06 07:26:21