求取vector中前n个最大值 c++

求取vector中前n个最大值

如果只是需要取出数组中一些最大或最小的元素,可以利用nth_element函数快速定位第k个元素,该函数也支持直接写比较函数,对其他元素并没有排序, 将第n元素放到它该放的位置上,左边元素都大于等于它,右边元素都小于等于它。

nth_element的空间复杂度为O(1),在数据量大的时候时间复杂度为O(n),数据少的情况最坏为O(n^2),因为函数原理是随机访问,如果实际数据是随机分布的中,基本都会是O(n)的时间复杂度,效率比全部排序完再取是高很多的。

#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include <vector>

using namespace std;

bool myfunction(int i, int j) {
	return (i>j);
}
int main() {
	vector<int> vector_1 = { 3,5,1,6,7,8,3,0,6,7 };
	int n = 5;
	nth_element(vector_1.begin(), vector_1.begin() + n, vector_1.end(), myfunction);
	for (int i = 0; i < vector_1.size(); i++)
		cout << vector_1[i] << " ";
	cout << '\n';
	return 0;
}

输出:8 7 7 6 6 5 3 3 1 0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章