前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >找出一个数组中出现次数最大的数

找出一个数组中出现次数最大的数

作者头像
猿人谷
发布2018-01-17 15:38:03
1.5K0
发布2018-01-17 15:38:03
举报
文章被收录于专栏:猿人谷猿人谷

描叙:一大堆数据里面,数字与数字之间用空格隔开,找出出现次数最多的一个数字的算法

#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++解法如下:

 1 #include<iostream>
 2 #include<map>
 3 #include<utility>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     map<int , int> word_count;
 9     int number;
10     while(cin>>number)
11     {
12         pair<map<int , int>::iterator , bool> ret = word_count.insert(make_pair(number , 1));
13         if(!ret.second)
14             ++ret.first->second;
15     }
16 
17     for(map<int , int>::iterator iter = word_count.begin() ; iter != word_count.end() ; ++iter)
18         cout<<(*iter).first<<"\t\t"
19             <<(*iter).second<<endl;
20 
21     return 0;
22 }

更简洁的方法如下:

 1 #include<iostream>
 2 #include<map>
 3 #include<utility>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     map<int , int> word_count;
 9     int number;
10 
11     while(cin>>number)
12         ++word_count[number];
13 
14     for(map<int , int>::iterator iter = word_count.begin() ; iter != word_count.end() ; ++iter)
15         cout<<(*iter).first<<"\t\t"
16             <<(*iter).second<<endl;
17 
18     return 0;
19 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-07-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档