眾數問題
http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/3015/pid/1710.html
Time Limit: 2000 ms Memory Limit: 65536 KiB
Problem Description
給定含有n個元素的多重集合S,每個元素在S中出現的次數稱為該元素的重數。多重集S中重數最大的元素稱為眾數。例如,S={1,2,2,2,3,5}。多重集S的眾數是2,其重數為3。對於給定的由n 個自然數組成的多重集S,計算S的眾數及其重數。如果出現多個眾數,請輸出最小的那個。
Input
輸入數據的第1行是多重集S中元素個數n(n<1300000);接下來的n行中,每行有一個最多含有5位數字的自然數,。
Output
輸出數據的第1行給出眾數,第2行是重數。
Sample Input
6 1 2 2 2 3 5
Sample Output
2 3
解決思路:
使用數組Arr[i],其中i表示輸入數據,Arr[i]表示i出現的個數。第一次循環輸入並找出眾數,而二次循環判斷i,找到最小的。
注意事項:
因為 索引i 與 Arr[i] 之間存在對應關系,此時如果調用Sort[i] 會破壞這種對應關系。另一種解決方法是使用 Arr[t[i]],對t[i]使用Sort()排序。
源代碼:
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 int arr[100005] = { 0 }; 5 6 bool cmp(int i, int j) { 7 return i > j; 8 } 9 int main() 10 { 11 int Count = 0; 12 int MostElem = 0; 13 int num; 14 int Elem; 15 16 std::cin >> num; 17 18 19 // 先輸入並計算 20 for (int i = 0; i < num; i++) { 21 std::cin >> Elem; 22 arr[Elem]++; 23 if (arr[Elem] > Count) { 24 Count = arr[Elem]; 25 } 26 } 27 28 // 若直接調用sort,則會破壞 i 與 arr[i] 之間的對應關系。 29 // 直接再從頭遍歷一遍 30 int temp = 100000; 31 for (int i = 0; i < 100000; i++) { 32 if (arr[i] == Count && i < temp){ 33 temp = i; 34 } 35 } 36 37 // 直接輸出 38 cout << temp << endl << Count << endl; 39 40 41 return 0; 42 }