http://blog.youkuaiyun.com/hyg0811/article/details/10797731
描叙:一大推数据里面,数字与数字之间用空格隔开,找出出现次数最多的一个数字的算法
- #include<stdio.h>
- void FindMostTimesDigit(int *Src , int SrcLen)
- {
- int element , has = SrcLen;
- int MaxNum , TempCount = 0 , MaxCount = 0;
- int i , j;
- int *result = new int[];
- while(has != 0)
- {
- element = Src[has - 1];
- TempCount = 0;
- for(i = has - 1 ; i >= 0 ; --i)
- {
- //如果找到,则计数加1 ,然后将数据和末尾交换
- //这也是为何要从末尾开始循环的理由
- if(element == Src[i])
- {
- TempCount++;
- Src[i] = 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(j = 0 ; j <= MaxNum ; ++j)
- printf("%d " , result[j]);
- 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>
- using namespace std;
- int main()
- {
- map<int , int> word_count;
- int number;
- while(cin>>number)
- {
- pair<map<int , int>::iterator , bool> ret = word_count.insert(make_pair(number , 1));
- if(!ret.second)
- ++ret.first->second;
- }
- for(map<int , int>::iterator iter = word_count.begin() ; iter != word_count.end() ; ++iter)
- cout<<(*iter).first<<"\t\t"
- <<(*iter).second<<endl;
- return 0;
- }
更简洁的方法如下:
- #include<iostream>
- #include<map>
- #include<utility>
- using namespace std;
- int main()
- {
- map<int , int> word_count;
- int number;
- while(cin>>number)
- ++word_count[number];
- for(map<int , int>::iterator iter = word_count.begin() ; iter != word_count.end() ; ++iter)
- cout<<(*iter).first<<"\t\t"
- <<(*iter).second<<endl;
- return 0;
- }