溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++100w個數中找出最大的前K個數

發布時間:2020-09-06 21:01:50 來源:網絡 閱讀:1260 作者:zgw285763054 欄目:編程語言

/*100w個數中找出最大的前K個數*/

#include <iostream>

using namespace std;

#include <assert.h>


const int N = 10000;

const int K = 100;


void AdjustDown(int topK[], int size, size_t parent)

{

assert(topK);


int child = parent*2 + 1;


while (child < size)

{

if (child+1 < size

&& topK[child+1] < topK[child])

{

++child;

}


if (topK[child] < topK[parent])

{

swap(topK[child], topK[parent]);


parent = child;

child = parent*2 + 1;

}

else

{

break;

}

}

}


void GetTopKValue(int array[], int topK[])

{

assert(K < N);


for (int i = 0; i < K; ++i)

{

topK[i] = array[i];

}


//建小堆

for (int i = (K-2)/2; i >= 0; --i)

{

AdjustDown(topK, K, i);

}


for (int i = K; i < N; ++i)

{

if (array[i] > topK[0])

{

topK[0] = array[i];

AdjustDown(topK, K, 0);

}

}


for (int i = 0; i < K; ++i)

{

cout<<topK[i]<<" ";


if (i%5 == 0)

{

cout<<endl;

}

}


cout<<endl;

}


void Test()

{

int array[N] = {0};

int topK[K] = {0};


for (int i = 0; i < N; ++i)

{

array[i] = i;

}

array[9] = 111111;

array[99] = 1111111;

array[999] = 11111111;

GetTopKValue(array, topK);

}


int main()

{

Test();

return 0;

}

C++100w個數中找出最大的前K個數

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女