試題請參見: http://acm.hdu.edu.cn/showproblem.php?pid=1004
題目概述
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges’ favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.
This year, they decide to leave this lovely job to you.
解題思路
最直觀的方法當然是開一個Map, 然後計數. 但是感覺太沒有計數含量.
之前看到過一道面試題, 說在有序的序列中用O(n)的時間複雜度找出出現次數最多的數.
所以問題便轉換爲, 先將這個序列變爲有序的序列(快速排序), 再使用O(n)的時間找出出現次數最多的顏色.
源代碼
#include <iostream>
#include <string>
const int MAX_SIZE = 1000;
std::string balloons[MAX_SIZE];
void quickSort(int left, int right) {
int i = left, j = right,
pivot = (left + right) / 2;
while ( i <= j ) {
while ( balloons[i] < balloons[pivot] ) ++ i;
while ( balloons[j] > balloons[pivot] ) -- j;
if ( i <= j ) {
std::swap(balloons[i ++], balloons[j --]);
} else {
break;
}
}
if ( left < j ) quickSort(left, j);
if ( i < right )quickSort(i, right);
}
int main(int argc, char* argv[]) {
int n = 0;
while ( std::cin >> n ) {
if ( n == 0 ) {
break;
}
for ( int i = 0; i < n; ++ i ) {
std::cin >> balloons[i];
}
quickSort(0, n -1);
std::string popularColor = balloons[0];
std::string previousColor = balloons[0];
int currentCount = 0;
int maxCount = 0;
for ( int i = 1; i < n; ++ i ) {
if ( previousColor == balloons[i] ) {
++ currentCount;
} else {
currentCount = 0;
}
if ( currentCount > maxCount ) {
maxCount = currentCount;
popularColor = previousColor;
}
previousColor = balloons[i];
}
std::cout << popularColor << std::endl;
}
return 0;
}