
HackerRank 生日蛋糕蜡烛问题详解及解法
本文将讲解 HackerRank 上的“生日蛋糕蜡烛”算法题,该题考察循环和数组操作。我们将学习如何分析问题,并给出 Python 和 C 语言的解决方案。
问题描述
你需要为孩子准备生日蛋糕,蛋糕上每根蜡烛代表孩子一岁的年龄。孩子只能吹灭最高的蜡烛。请计算有多少根最高的蜡烛。
简而言之,就是求数组中最大元素出现的次数。
输入格式
n:蛋糕上蜡烛的总数(整数)。ar:一个包含 n 个整数的数组,表示每根蜡烛的高度。输出格式
Python 解法
<code class="python">def birthdayCakeCandles(candles):
"""
计算生日蛋糕上最高蜡烛的数量。
Args:
candles: 一个包含蜡烛高度的整数列表。
Returns:
最高蜡烛的数量。
"""
max_height = max(candles) # 找到最高蜡烛的高度
count = candles.count(max_height) # 统计最高蜡烛的数量
return count
# 示例用法
candles = [4, 4, 1, 3]
result = birthdayCakeCandles(candles)
print(result) # 输出:2</code>Python 解法说明
max(candles):直接使用 Python 内置的 max() 函数找到列表中最大的元素(最高蜡烛高度)。candles.count(max_height):使用列表的 count() 方法统计最大值出现的次数。C 解法
<code class="c">#include <stdio.h>
int birthdayCakeCandles(int candles[], int n) {
int max_height = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (candles[i] > max_height) {
max_height = candles[i];
count = 1; //重置计数器
} else if (candles[i] == max_height) {
count++;
}
}
return count;
}
int main() {
int candles[] = {4, 4, 1, 3};
int n = sizeof(candles) / sizeof(candles[0]);
int result = birthdayCakeCandles(candles, n);
printf("%d\n", result); // 输出:2
return 0;
}</code>C 解法说明
max_height 和 count。max_height,并记录其出现次数 count。两种解法都清晰地解决了问题,Python 解法更简洁,而 C 解法更底层,体现了对数组操作的理解。 选择哪种解法取决于你的编程语言偏好和对算法效率的要求。 对于这个问题来说,两种方法的效率差异微乎其微。
以上就是生日蛋糕蜡烛 - HackerRank 问题解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号