眾數問題(山東理工OJ)

來源:互聯網
上載者:User

題目描述
給定含有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**************************************/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.