nth_element() O(n)
nth_element(a.begin(),a.begin()+n,a.end());把数组中比a[n]小的数移动到a[n]前面,比a[n]大的数移动到后面,从a[0]开始
不一定有序
#include<iostream>
#include<algorithm>
#include<cstring>
#include<iomanip>
#include<vector>
#include<cmath>
#include<ctime>
#define IOS std::ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);
#define pi acos(-1);
using namespace std;
typedef struct node{
}node;
int main(){
IOS;
vector<int>v1;
for(int i=1;i<=5;i++){
int a;cin>>a;
v1.push_back(a);
}
nth_element(v1.begin(),v1.begin()+2,v1.end());
for(auto it=v1.begin();it!=v1.end();it++)cout<<*it<<endl;
return 0;
}
示例代码演示了如何使用C++中的nth_element函数,该函数在平均时间复杂度为O(n)的情况下,将数组中第n个元素定位到正确位置,使得其前面的元素都小于它,后面的元素都大于它,无需完全排序。
3350

被折叠的 条评论
为什么被折叠?



