Leetcode 1103. Distribute Candies to People

2022-08-11 15:03:01 浏览数 (1)

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

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞