今天課上實驗課,遇到一道題目,需要查找一個數組中出現次數最多的元素和次數,並且輸出。第一次用struct模擬字典,十分麻煩而且復雜度是O(n*n)。其實,運用轉化的思想,可以先將其排序,然后再查找即可,時間復雜度之后只有O( n*log_2(n))。
題目是這樣的:
某小鎮要票選鎮長,得票最高者當選。但由於投票機制不健全,導致每屆投票時,候選人在投票系統的識別碼類型不一致。請編寫函數模板,能針對多種類型的數據,查找出得票最高的元素。其中,每屆投票的選票有n張,識別碼類型為T
注意:必須使用模板函數
輸入:
3
I 10
5 3 5 2 9 7 3 7 2 3
C 8
a b a e b e e q
S 5
sandy david eason cindy cindy
輸出:
3 3
e 3
cindy 2
代碼實現:算法在findMax函數實現
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
template <class T>
void findMax(T* arr,int len){
int j;
for(j=0;j<len;++j)
cin>>arr[j];
sort(arr,arr+len);
int times=0 ,tem_times=1;
T elem=arr[0] ;
for(j = 1;j<len;++j)
if(arr[j]==arr[j-1])
tem_times++;
else{
if(tem_times>times){
times = tem_times;
elem = arr[j-1];
}
tem_times = 1;
}
if(tem_times>times){
elem = arr[len-1];
times = tem_times;
}
cout<<elem<<" "<<times<<endl;
}
int main(){
int t,num;
cin>>t;
char type;
while(t--){
cin>>type;
cin>>num;
if(type=='I'){
int *arr = new int [num];
findMax(arr,num);
}
else if(type=='S'){
string *arr = new string [num];
findMax(arr,num);
}
else if(type=='D'){
double *arr = new double [num];
findMax(arr,num);
}
else{
char *arr = new char [num];
findMax(arr,num);
}
}
return 0;
}
歡迎進一步交流本博文相關內容:
博客園地址 : http://www.cnblogs.com/AsuraDong/
CSDN地址 : http://blog.csdn.net/asuradong
也可以致信進行交流 : xiaochiyijiu@163.com
歡迎轉載 , 但請指明出處 : )