您的位置:首页 > 其它

HDOJ1004.Let the Balloon Rise

2015-09-15 10:22 197 查看
试题请参见: 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: