HDOJ1004.Let the Balloon Rise

试题请参见: 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值