找出出現次數最多的一個數字的算法
#include<stdio.h> void FindMostTimesDigit(int *Src , int SrcLen) { int element , has = SrcLen; int MaxNum , TempCount = 0 , MaxCount = 0; int i , j , *result = new int[]; while(0 != has) { TempCount = 0; element = Src[has - 1]; for(j = has - 1 ; j >= 0 ; --j) { // 如果找到,則計數加1,然後將數據和末尾交換 // 這也是為何要從末尾開始循環的理由 if(element == Src[j]) { TempCount++; // 把後面的數據移動到前面來 Src[j] = Src[has - 1]; has--; } } if(TempCount > MaxCount) { MaxCount = TempCount; MaxNum = 0; result[MaxNum] = element; } else if(TempCount == MaxCount) { result[++MaxNum] = element; } } printf("出現最多的次數:%d\n" , MaxCount); for(i = 0 ; i <= MaxNum ; ++i) { printf("%d " , result[i]); } printf("\n"); } int main() { int list[]={1,2,3,4,3,3,2,2,1,1,4,4,4,1,2}; int length =sizeof(list) / sizeof(int); FindMostTimesDigit(list, length); return 0; }
C++解法如下:
#include<iostream> #include<map> #include<utility> map< , > (cin>> pair<map< , >::iterator , > ret = word_count.insert(make_pair(number , (! ++ret.first-> (map< , >::iterator iter = word_count.begin() ; iter != word_count.end() ; ++ cout<<(*iter).first<< <<(*iter).second<< }
更簡潔的方法如下:
#include<iostream> #include<map> #include<utility> map< , > (cin>> ++ (map< , >::iterator iter = word_count.begin() ; iter != word_count.end() ; ++ cout<<(*iter).first<< <<(*iter).second<< }
網上看到一哥們也寫了類似的東西:http://blog.csdn.net/tianmohust/article/details/7514618