尋找最大的k個數,TopK問題的C 實現

2021-06-08 02:36:59 字數 3030 閱讀 8060

2億個整數中求最大的100萬之和

題目:有乙個檔案中儲存了2億個整數,每個整數都以' '分隔。求最大的100萬個整數之和。

演算法:1. 首先建立乙個容量為100萬(ntop)的int陣列,從檔案讀取整數填充。

2. 利用堆維護該100萬條記錄(確保堆頂元素為最小值)

3. 從檔案中讀取乙個整數與堆頂元素比較,如果大於堆頂元素則替換該元素,並調整堆的結構。

4. 重複步驟3一直到資料讀取完

5. 將陣列中的元素全部相加,得到結果

參考源**:

#include using namespace std;

templateclass ctopk

;templatectopk::ctopk()

templatectopk::~ctopk()

templatevoid ctopk::clear()

}//獲取前top的k個數

templateint ctopk::gettopk(const char* sfile, int& ntop)

//清除操作

clear();

//開啟檔案

fp = fopen(sfile, "r");

if (null == fp)

//分配空間

m_data = new t[ntop];

if (null == m_data)

cout << "please wait..." << endl;

//讀取前ntop個資料,注意資料的型別t

for (i = 0; i < ntop; i++)

else

}//最大的個數小於ntop,求前i個資料

if (i < ntop)

else}}

return 0;

}//調整小根堆,堆頂為top k最小

templatevoid ctopk::heapadjust(int nstart, int nlen)

}//change data

if (m_data[nstart] > m_data[nminchild])

else

}}//建立堆

templatevoid ctopk::buildheap(int nlen)

}int main(int argc, char* argv)

; int nnum = 0;

ctopkobjtopsum;

cout << "please input count file name:" << endl;

cin >> szfile;

cout << "please input top num:"<< endl;

cin >> nnum;

objtopsum.gettopk(szfile, nnum);

int fsum = 0;

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

; struct node_has_space

;

// 最簡單hash函式

int hash_function(const char *p)

return value;

}

// 新增單詞到hash表

p = p->next;

} // 新建乙個結點

ptr_no_space q = new node_no_space;

q->count = 1;

q->word = new char [strlen(str)+1];

strcpy(q->word, str);

q->next = head[index];

head[index] = q;

}

// 將單詞處理結果寫入檔案

void write_to_file()

fclose(fp);

}

// 從上往下篩選,保持小根堆

void sift_down(node_has_space heap, int i, int len)

} // 建立小根堆

void build_min_heap(node_has_space heap, int len)

// 去除字串前後符號

void handle_symbol(char *str, int n)

while (str[0] < '0' || (str[0] > '9' && str[0] < 'a') || (str[0] > 'z' && str[0] < 'a') || str[0] > 'z')

str[i] = '\0';

n--;

} }

int main()

fclose(fp_passage);

// 將統計結果輸入檔案

write_to_file();

int n = 10;

ptr_has_space heap = new node_has_space [n+1];

int c;

file *fp_word = fopen("result.txt", "r");

assert(fp_word);

for (int j = 1; j <= n; j++)

// 建立小根堆

build_min_heap(heap, n);

// 查詢出現頻率最大的10個單詞

while (fscanf(fp_word, "%s %d", &str, &c) != eof)

} fclose(fp_word);

// 輸出出現頻率最大的單詞

for (int k = 1; k <= n; k++)

cout << heap[k].count << " " << heap[k].word << endl;

return 0;

}

參考:

尋找最大的K個數 TOP K演算法

前言 本文是對程式設計之美第2.5節以及博文的一些總結和心得 問題描述 有很多個無序的數,怎麼從中選出其中最大的若干數呢?這個問題中的很多可以是幾個數也可以使成百上億的數,針對此問題我們有以下解法 解法一 咱們先簡單的理解,要求乙個序列中最小的k個數,按照慣有的思維方式,很簡單,先對這個序列從小到大...

尋找最大的K個數,Top K問題的堆實現

參考 如果不能把所有資料的資料都一次性放入記憶體,就可以維護乙個大小為k的堆,找最大的k個數,就維護乙個小根堆,堆頂元素為這最大的k個數中的最小元素。具體實現參考下面兩個例子 2億個整數中求最大的100萬之和 題目 有乙個檔案中儲存了2億個整數,每個整數都以 分隔。求最大的100萬個整數之和。演算法...

尋找最大的K個數

方法一 改進的快速排序 分割槽時,根據數p將陣列分為兩部分,設大於p的數個數為a,小於p的數的個數為b。如果,a k,則從這a個數取最大的k個數,若a時間複雜度是o nlogk include includevoid swap float a,float b int fun float n,int ...