題目:輸入n個整數,找出其中最小的k個數。例如輸入4、5、1、6、2、7、3、8這8個數字,則最小的4個數字是1、2、3、4。
方法一:根據陣列特點找出時間複雜度為o(n)的演算法
#include#includeusing namespace std;
int randomofrange(int start, int end);
int partition(int* numbers, int length, int start, int end);
void swap(int* a, int* b);
//基於partition函式:當陣列的第k個數字左邊的數字都小於該第k個數字
//則列印前k個數字;否則繼續呼叫partition函式對陣列進行排列
void getleastnumbers(int* numbers, int length, int k)
else
}for (int i = 0;i < k;++i)
cout << numbers[i] << " ";
cout << endl;
}//對陣列進行排列
int partition(int* numbers, int length, int start, int end)
} ++small;
swap(&numbers[small], &numbers[end]);
return small;
}//隨機返回乙個在範圍內的數
int randomofrange(int start, int end)
//交換兩數
void swap(int* a, int* b)
//測試輸入
void test1()
; getleastnumbers(numbers, sizeof(numbers) / sizeof(numbers[0]), 4);
}// 不存在出現次數超過陣列長度一半的數字
void test2()
; getleastnumbers(numbers, sizeof(numbers) / sizeof(numbers[0]), 4);
}// 出現次數超過陣列長度一半的數字都出現在陣列的前半部分
void test3()
; getleastnumbers(numbers, sizeof(numbers) / sizeof(numbers[0]), 4);
}// 出現次數超過陣列長度一半的數字都出現在陣列的後半部分
void test4()
; getleastnumbers(numbers, sizeof(numbers) / sizeof(numbers[0]), 4);
}// 輸入空指標
void test5()
int main(int argc, char* argv)
方法二:基於紅黑樹的multiset實現,時間複雜度為o(nlogk),適合處理海量資料
#include#include#include#include #include using namespace std;
//定義從大到小排序的intset和對應的迭代器setiterator
typedef multiset> intset;
typedef multiset>::iterator setiterator;
void getleastnumbers(const vector& data, intset& leastnumbers, int k)
} }}//輸入測試
void test1()
; intset leastnumbers;
getleastnumbers(data, leastnumbers, 4);
for (auto iter = leastnumbers.begin();iter != leastnumbers.end();++iter)
cout << *iter << " ";
cout << endl;
}void test2()
; intset leastnumbers;
getleastnumbers(data, leastnumbers, 4);
for (auto iter = leastnumbers.begin();iter != leastnumbers.end();++iter)
cout << *iter << " ";
cout << endl;
}void test3()
; intset leastnumbers;
getleastnumbers(data, leastnumbers, 8);
for (auto iter = leastnumbers.begin();iter != leastnumbers.end();++iter)
cout << *iter << " ";
cout << endl;
}void test4()
; intset leastnumbers;
getleastnumbers(data, leastnumbers, 0);
for (auto iter = leastnumbers.begin();iter != leastnumbers.end();++iter)
cout << *iter << " ";
cout << endl;
}void test5()
; intset leastnumbers;
getleastnumbers(data, leastnumbers, 9);
for (auto iter = leastnumbers.begin();iter != leastnumbers.end();++iter)
cout << *iter << " ";
cout << endl;
}int main(int argc, char* argv)
最小的K個數
問題描述 給定的n個整數,計算其中最小的k個數。最直觀的解法莫過於將n個數按公升序排列後輸出前k個。但是就效率來看,這種方法並不是最理想的。一種改進方法是借助快速排序中對陣列的劃分,以第k個元素對陣列進行劃分,使得比第k個數字小的數字都在其左邊,比其大的數字都在它的右邊。void swap int ...
最小的K個數
從 陣列中出現次數超過一半的數字 得到啟發,同樣可以基於partition函式來解決。一 o n 演算法 void getleastnumbers int input,int n,int output,int k else for int i 0 i k i output i input i 二 o...
最小的K個數
輸入n個整數,找出其中最小的k個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,如果不讓使用sort的話,自己實現乙個,或者依次選取最小的 class solution public vectorgetleastnumbers solution vectori...