找出一個數組中出現次數最大的數


描敘:一大堆數據里面,數字與數字之間用空格隔開,找出出現次數最多的一個數字的算法

 

#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 }

 

網上看到一哥們也寫了類似的東西:http://blog.csdn.net/tianmohust/article/details/7514618


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM