unique和lower_bound的用法

//第k小整数 c++写法
#include<cstdio>
#include<algorithm>
using namespace std;
int a[10001];

int main(){
int n,k;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
sort(a,a+n);
int m=unique(a,a+n)-a;
//先确定数组有序再使用unique,否则先排序
//unique 两个参数是区间左右端点 左闭右开
//unique返回值:去重以后的尾地址 再减去首地址得size
//使用unique以后的数组:不重复的元素移到了前面 size以后位置的元素和之前一样
if(k>m){
printf("NO RESULT\n");
return 0;
}
int ans=upper_bound(a,a+m,a[k-2])-a;
///lower/upper_bound(begin,end,num);
//lower从begin到end-1查找,找到第一个大于等于num的数 返回该数的地址 不存在则返回end
//upper从begin到end-1查找,找到第一个大于num的数 返回该数的地址 不存在则返回end
//通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

//<=> printf("%d\n",a[k-1]);
printf("%d\n",a[ans]);
return 0;
}

posted @ 2021-03-28 12:53  starlightlmy  阅读(88)  评论(0)    收藏  举报