Leetcode 1103. Distribute Candies to People

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1103. Distribute Candies to People相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

2. Solution

**解析:**Version 1,循环遍历即可,current为当前这次要分配的糖果数量,每次要分配的糖果数量加1,如果不够,则剩余糖果分配给最后一个。

  • Version 1
class Solution:
    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        result = [0] * num_people
        index = 0
        current = 1
        while candies > 0:
            current = min(current, candies)
            result[index % num_people] += current
            candies -= current
            current += 1
            index += 1
        return result

**解析:**Version 2,index可以用current替代。

  • Version 2
class Solution:
    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        result = [0] * num_people
        current = 1
        while candies > 0:
            result[(current - 1) % num_people] += min(current, candies)
            candies -= current
            current += 1
        return result

Reference

  1. https://leetcode.com/problems/distribute-candies-to-people/

以上是关于Leetcode 1103. Distribute Candies to People的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode.1103-向人们分发糖果(Distribute Candies to People)

Leetcode 1103. Distribute Candies to People

Leetcode 1103. Distribute Candies to People

Leetcode 1103. Distribute Candies to People

LeetCode 1103. Distribute Candies to People (分糖果 II)

[LeetCode] 1103. Distribute Candies to People 分糖果