求取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

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