在hackerrank生日蛋糕蜡烛问题中使用std :: vector

Posted

技术标签:

【中文标题】在hackerrank生日蛋糕蜡烛问题中使用std :: vector【英文标题】:Using std::vector in hackerank birthday cake candles question 【发布时间】:2019-07-22 08:25:18 【问题描述】:

我已经使用数组解决了这个问题,但无法使用向量来解决。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() 

    int age, count = 0, i;
    vector<int>length;
    cin >> age;

    for (i = 0; i <= age; i++)
    
        length.push_back(i);
    
    sort(length.begin(), length.end());

    int max = length.back();
    for (i = 0; i <= length.size(); i++)
    
        if (length[i] == max)
            count++;
    
    cout << count;
    return 0;

我希望在第一个测试用例中输出为2,但实际输出为1

这就是问题 - https://www.hackerrank.com/challenges/birthday-cake-candles/problem

【问题讨论】:

如果你推回 0、1、2、...、年龄,那么对向量进行排序是没有意义的 如果事先知道大小,习惯length.reserve(age + 1);这样,您可以防止多次重新分配(包括复制所有数据)。 阅读问题: 1. 使用i = 0; i &lt;= age,您创建一根蜡烛太多(尝试在您的脑海中使用age = 2:您将为i == 0i == 1 和@987654330 创建蜡烛@. 2. 根本不需要向量:读取第一个蜡烛作为参考,然后读取所有其他蜡烛,如果大小等于当前,则增加一个计数器,如果大小更大,将此计数器重置为 1... 【参考方案1】:

根据问题(在链接的网站中),您错过了n,它表示蛋糕上的蜡烛数量。

你错过了。此外,您不会将 height 推回向量中(不是 age)。应该是

int n; 
std::cin>> n;  //>>>> this

for(int i=0; i<n; i++)  // where n is the number of candles on the cake: equalent to the `age` of the girl

    int height; std::cin >> height; // height of each candles
    length.push_back(height);

完整的代码如下所示:

#include <iostream>
#include <algorithm>
#include <vector>

int main()

    int n;  std::cin >> n;  //>>>> you missed this
    std::vector<int> length;
    length.reserve(n);      // reserve the memory, as you know the size

    for (int i = 0; i < n; i++)  // where n is the number of candles on the cake: equalent to the `age` of the girl
    
        int height; std::cin >> height;  // height of each candles
        length.push_back(height);
    
    std::sort(length.begin(), length.end());
    // see the `const` as `max` will not change latter in the program
    const int max = length.back();  

    int count = 0;
    for (const int element : length) // use range based for-loop, if possible
    
        if (element == max) count++;
    
    std::cout << count;
    return 0;


但是,如果可以找到用户输入中的最大元素,则在输入时,您可以避免调用std::sort。另外,还有一个标准的算法函数叫做std::count,它也可以用来查找已经找到的最大元素的计数,如下所示。

#include <iostream>
#include <algorithm> // std::max, std::count
#include <vector>
#include <numeric>   // std::numeric_limits

int main()

    int n;  std::cin >> n; // the number of candles on the cake
    std::vector<int> length;
    length.reserve(n);    // reserve the memory, to avoid un-wanted reallocations
    // set the maximum to INT_MIN
    int max = std::numeric_limits<int>::min();
    while (n--)
    
        int element;  std::cin >> element;
        length.emplace_back(element);
        // while  inserting to the vector find the maximum element
        max = std::max(element, max);
    
    // using std::count find the count of `max` element and print!
    std::cout << std::count(length.cbegin(), length.cend(), max);
    return 0;


注意:避免使用using namespace std; 练习。更多阅读:Why is "using namespace std;" considered bad practice?

【讨论】:

【参考方案2】:
int main()

    int age, count=0; //, i; // keep variables as local as possible!
    std::vector<int> length;
    std::cin >> age;

    // you don't check for stream state nor validity of `age`:
    if(!std::cin || age < 0) // possibly some upper limit, too??
                             // side note: if you use unsigned int, you only have
                             // to check this upper limit!
    
        // some appropriate error handling
    

    // optimisation: we know necessary capacity in advance, so let's prevent
    // otherwise necessary re-allocations:
    length.reserve(age);

    //for(i=0;i<=age;i++)
    for(int i = 0; i < age; i++) // variables as local as possible, remember?
                                 // <= reads one candle too much; consider age == 2:
                                 // you'll get candles for i == 0, i == 1 and i == 2!
    
        // well no, you don't want to push back the counter itself (0, 1, 2, ...)
        // you need to read in candle hights instead!
        //length.push_back(i);
        int height;
        std::cin >> height;
        // check input as before!
        length.push_back(height);
    
    std::sort(length.begin(), length.end());

    int max = length.back();

    // for(i=0;i<=length.size(); i++)
    //           ^ again, one element too much!
    // ...

嗯,在这一点上,你可以更聪明一些;你已经排序了,所以从中获利!使用迭代器更简单,可以直接从后面迭代!

for(auto i = length.rbegin(); i != length.rend(); ++i)

    if(*i != max)
    
        count = i - length.rbegin();
        break;
    

// special case: all candles have same height, then you would't have met the inner if:
if(count == 0)

    count = length.size();

实际上,您无需先排序就可以一次完成:

int max = 0; // now let's assume we checked for negative values right from the start
             // otherwise we'd need to use std::numeric_limits<int>::min() instead
             // again I'd prefer the unsigned type...
for(auto height : length)

    if(height == max)
        ++count;
    else if(height > max)
        count = 1;
    // else: can ignore...

嗯……你注意到了吗?我们只是按照与读取值相同的顺序进行处理。所以我们可以一次性完成所有工作:

for(int i = 0; i < age; ++i)

    unsigned int height;
    std::cin >> height;
    // check validities!

    // instead of pushing back, directly calculate what we are interested in:
    if(height == max)
        ++count;
    else if(height > max)
        count = 1;

【讨论】:

【参考方案3】:

您正在超出向量的末端。使用

for(i=0; i    <    length.size(); i++)

【讨论】:

【参考方案4】:
#include<iostream>
#include<algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define max 100000
int main()

    int a[max],i,n,count=0,key;
    cin>>n;
    for(i=0;i<n;i++)
    
        cin>>a[i];
    
    
        sort(a, a+n);
    for(i=0;i<n;i++)
    
        key=a[n-1];
        if(key==a[i])
        
            count=count+1;
        
    
    cout<<count;

【讨论】:

欢迎来到 Stack Overflow。在 Stack Overflow 上不鼓励仅使用代码的答案,因为它们没有解释它是如何解决问题的。请编辑您的答案以解释此代码的作用以及它如何回答问题,以便对其他有类似问题的用户有用。

以上是关于在hackerrank生日蛋糕蜡烛问题中使用std :: vector的主要内容,如果未能解决你的问题,请参考以下文章

2.生日蜡烛

生日蜡烛(蓝桥杯)

蓝桥杯-生日蜡烛

java算法 蓝桥杯(题+答案) 生日蜡烛

LQ0031 生日蜡烛枚举

生日蜡烛 (结果填空)