#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n;
int a[N];
int q[N];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
int len = 0;
for (int i = 0; i < n; i ++ )
{
int l = 0, r = len;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (q[mid] < a[i]) l = mid;
else r = mid - 1;
}
len = max(len, r + 1);
q[r + 1] = a[i];
}
printf("%d\n", len);
return 0;
}
对比下面的二分:
int len=0;
q[0]=-1e9;//因为有负值,第0个数还是要设一个最小值
for(int i=0;i<n;i++){
int l=0,r=len+1;//左闭右开
while(l<r){
int mid=l+r>>1;
if(q[mid]>=a[i]) r=mid;
else l=mid+1;
}
len=max(len,l);//这里r和l都可以,因为左闭右开保证能进入while循环
q[l]=a[i];
}
printf("%d\n",len);