HDOJ1004.Let the Balloon Rise
2015-09-15 10:22
197 查看
试题请参见: http://acm.hdu.edu.cn/showproblem.php?pid=1004
This year, they decide to leave this lovely job to you.
之前看到过一道面试题, 说在有序的序列中用O(n)的时间复杂度找出出现次数最多的数.
所以问题便转换为, 先将这个序列变为有序的序列(快速排序), 再使用O(n)的时间找出出现次数最多的颜色.
题目概述
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; }
相关文章推荐
- Cordova for iOS —— 创建Cordova工程
- 【PA2014Final】【BZOJ3721】Bazarek
- Linux之cron任务
- %02f前面却出现很多6个f
- jQuery与MooTools库的一些比对
- 深度学习的局限
- 八皇后问题
- windows不同场景下的系统会话与系统进程
- Android之xml解析
- HDU 5437 Alisha’s Party(优先队列+模拟)
- 网站分类前导:获取网站标题和描述及对相关信息进行分词处理
- 8月“.中国”域名总量净减2,045个 降幅明显增大
- 网站分类前导:获取网站标题和描述及对相关信息进行分词处理
- C++全局函数与类成员函数的区别和相互转化
- java实现的文件压缩和解压
- word转pdf还有什么好的方法
- Java接口类只能声明静态属性
- iOS界面设计切图小结
- Android手机 Fildder真机抓包
- 一个球从100m高度自由落下,每次落地后反跳回原来高度的一半,再落下,再反弹。 求它在第10次落地时,共经过多少米?第10次反弹多高?