寻找最大的K个数

本文介绍了一种高效的查找算法,适用于所有输入均为正整数且数值范围有限的情况。通过使用计数排序的思想,该算法能在O(n)的时间复杂度内找出数组中第k大的元素。此外,文章还提供了一个利用最大堆来寻找第k小元素的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解法五

复杂度O(n),应用场合为,所有的N个数都是正整数,取值范围不大。

代码如下:

 

下面使用最大堆求k min,

/*  
* Copyright (c) 2011 alexingcool. All Rights Reserved.  
*/ 
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

#define INF 65535

int array[] = {1111, 22222, 3000, 4, 34, 313, 13, 132409, 340, 43, 588, 30, 2,
237, 999, 90, 3, 5, 1, 7, 8};
const int size = sizeof array / sizeof *array;

const int heapSize = 4;
int maxHeap[heapSize];

void keepHeap(int (&heap)[heapSize], int pos)
{
	if(pos >= heapSize)
		return;

	int maxPos = pos;

	if(2 * pos + 1 < heapSize && heap[pos] < heap[2 * pos + 1])
		maxPos = 2 * pos + 1;
	if(2 * pos + 2 < heapSize && heap[maxPos] < heap[2 * pos + 2])
		maxPos = 2 * pos + 2;

	if(maxPos != pos) {
		swap(heap[pos], heap[maxPos]);
		keepHeap(heap, maxPos);
	}
}

void keepHeap2(int (&heap)[heapSize], int pos)
{
	if(pos >= heapSize)
		return;

	while(pos < heapSize) {
		int maxPos = pos * 2 + 1;
		
		if(maxPos >= heapSize)
			break;

		if(maxPos + 1 < heapSize && heap[maxPos] < heap[maxPos + 1])
			maxPos++;
		if(heap[pos] < heap[maxPos]) {
			swap(heap[pos], heap[maxPos]);
			pos = maxPos;
		} else
			break;
	}
}

void process(int (&array)[size])
{
	for(int i = 0; i < heapSize; i++) {
		maxHeap[i] = INF;
	}

	for(int i = 0; i < size; i++) {
		if(*maxHeap > array[i]) {
			*maxHeap = array[i];
			keepHeap2(maxHeap, 0);
			copy(maxHeap, maxHeap + heapSize, ostream_iterator<int>(cout, " "));
			cout << endl;
		}
	}
}

void main()
{
	cout << "----------------------------------------------------------------------" << endl;
	process(array);
	cout << "----------------------------------------------------------------------" << endl;
	
	cout << "result:" << endl;
	copy(maxHeap, maxHeap + heapSize, ostream_iterator<int>(cout, " "));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值