題目描述
給定含有n個元素的多重集合S,每個元素在S中出現的次數稱為該元素的重數。多重集S中重數最大的元素稱為眾數。例如,S={1,2,2,2,3,5}。多重集S的眾數是2,其重數為3。對於給定的由n 個自然數組成的多重集S,計算S的眾數及其重數。
輸入
輸入資料的第1行是多重集S中元素個數n(n<1300000);接下來的n行中,每行有一個最多含有5位元字的自然數,。
輸出
輸出資料的第1行給出眾數,第2行是重數。
樣本輸入
6
1
2
2
2
3
5
樣本輸出
2
3
#include <iostream>#include <algorithm>using namespace std;int main(void){ int n; while(cin>>n)//資料的個數 { int *array = new int [n+3];//多分配3個空間,避免數組越界 for(int i=0; i<n; i++) cin>>array[i];//輸入資料 sort(array,array+n);//升序排列 int index = 0,count_max = 1,count_temp = 1;//眾數下標,重數,臨時重數 for(int i=1; i<n; i++) if( array[i-1] != array[i]) { if( count_max < count_temp ) { count_max = count_temp;//記錄重數 index = i-1;//記錄眾數的下標 } count_temp = 1;//臨時重數清零 } else count_temp++; if( count_max < count_temp )//若眾數出現在最後面,則上面無法判斷,所以要增加一次判斷 { count_max = count_temp; index = n-1;//若眾數出現在最後面,那麼其下標就是n-1 } cout<<array[index]<<endl<<count_max<<endl; delete [] array; } return 0;}/**************************************Problem id: SDUT OJ 1710User name: 李俊Result: AcceptedTake Memory: 5284KTake Time: 480MSSubmit Time: 2014-04-23 00:12:07**************************************/