1. 题目描述
拥有最多糖果的孩子
给你一个数组candies和一个整数extraCandies,其中candies[i]代表第 i 个孩子拥有的糖果数目。
对每一个孩子,检查是否存在一种方案,将额外的extraCandies个糖果分配给孩子们之后,此孩子有最多的糖果。注意,允许有多个孩子同时拥有最多的糖果数目。
- 2 <= candies.length <= 100
- 1 <= candies[i] <= 100
- 1 <= extraCandies <= 50
Kids With the Greatest Number of Candies
There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.
Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.
Note that multiple kids can have the greatest number of candies.
- n == candies.length
- 2 <= n <= 100
- 1 <= candies[i] <= 100
- 1 <= extraCandies <= 50
2. 题解
2.1 C实现
2.1.1 解法一
底层逻辑:
提供额外糖果给某个孩子时,即便其原本并未拥有最多糖果,此时也有可能是拥有最多糖果的孩子,而判断当前孩子是否拥有最多糖果的前提是已知剩余孩子中拥有的最多糖果的数量。
代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies,
int* returnSize) {
bool* out = calloc(candiesSize, sizeof(bool));
*returnSize = candiesSize;
int max_value = 0;
for (int i = 0; i < candiesSize; i++) {
if (candies[i] > max_value) {
max_value = candies[i];
}
}
for (int i = 0; i < candiesSize; i++) {
if (candies[i] + extraCandies >= max_value) {
out[i] = true;
}
}
return out;
}
代码逻辑梳理:
- 初始化存放结果的内存(结果中包含该孩子加上额外糖果后是否为拥有最多糖果的孩子),并初始化为0(相当于false)。
- 设置返回结果的长度。
- 遍历全部孩子,找到拥有最多的糖果数量。
- 尝试将额外糖果给每一个孩子,判断其糖果数量是否是最多的,是的话设置其对应结果值为true。
- 返回处理结果。
复杂度分析:
时间复杂度:O(n)。
空间复杂度:O(n)。
2.2 Rust实现
第二轮刷题后完善。