HDOJ1004.Let the Balloon Rise,lettheballoonrise

來源:互聯網
上載者:User

HDOJ1004.Let the Balloon Rise,lettheballoonrise

試題請參見: 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;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.