1. 程式人生 > >hackerrank初級篇之Birthday Cake Candles

hackerrank初級篇之Birthday Cake Candles

題目說明:


示例程式碼:

// birthdayCakeCandles.cpp: 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <windows.h>
#include <vector>
#include <iostream>
using namespace std;

//by zhaocl
int birthdayCakeCandles( int n, vector<int>arr )
{
    //find max num
    int maxNum = 0;
    int times = 0;

    for( int i = 0; i < n; i++ )
    {
        if( maxNum <= arr[i] )
            maxNum = arr[i];
    }

    //find times
    for( int i = 0; i < n; i++ )
    {
        if( maxNum == arr[i] )
            times++;
    }

    return times;
}

//by apghr
int birthdayCakeCandleMore( int n, vector<int>arr )
{
    int num = 0;
    int maxnum = 0;
    int c = 0;

    while( n-- )
    {
        if( maxnum < arr[n] )
        {
            maxnum = arr[n];
            c = 1;
        }
        else
        {
            if( maxnum == arr[n] )
                c++;
        }
    }

    return c;
}

//by apghr
int birthdayCakeCandleBetter( int n, vector<int>arr )
{
    int max = 0;
    int c = 0;

    while( n-- )
    {
        max < arr[n] ? c = !!( max = arr[n] ) : c += max == arr[n];
    }

    return c;
}
int main()
{
    int n = 0;
    int times = 0;
    cin >> n;
    vector<int> arr( n );

    for( int i = 0; i < n; i++ )
    {
        cin >> arr[i];
    }

    //times = birthdayCakeCandles(n, arr);
    //times = birthdayCakeCandleMore(n, arr);
    times = birthdayCakeCandleBetter( n, arr );
    cout << times << endl;
    system( "pause" );
    return 0;
}