【LeetCode 75】【学习笔记】拥有最多糖果的孩子(Kids With the Greatest Number of Candies)

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;
}

代码逻辑梳理:

  1. 初始化存放结果的内存(结果中包含该孩子加上额外糖果后是否为拥有最多糖果的孩子),并初始化为0(相当于false)。
  2. 设置返回结果的长度。
  3. 遍历全部孩子,找到拥有最多的糖果数量。
  4. 尝试将额外糖果给每一个孩子,判断其糖果数量是否是最多的,是的话设置其对应结果值为true。
  5. 返回处理结果。

复杂度分析:
时间复杂度:O(n)。

空间复杂度:O(n)。

2.2 Rust实现

第二轮刷题后完善。

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Swordup

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值