LeetCodeMathdistribute candies to people分糖问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCodeMathdistribute candies to people分糖问题相关的知识,希望对你有一定的参考价值。

题目:

共有candies颗糖果,n=num_people个人,我们会按照以下方法分发糖果:

我们给第一个人一颗糖果,第二个人两颗糖果,依此类推,直到最后一个人给n颗糖果。

然后,我们返回到行的开头,将n +1颗糖果分配给第一个人,将n + 2颗糖果分配给第二个人,依此类推,直到将2 * n颗糖果分配给最后一个人。

重复此过程(每次我们多给一颗糖果,并在到达终点后移到行的开头),直到糖果用完。 最后一个人将收到我们所有剩余的糖果(不一定比以前的人多一颗)。返回一个数组(长度为num_people个糖果,总和为糖果),该数组代表糖果的最终分布。

Example 1:

Input: candies = 7, num_people = 4
Output: [1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].

Example 2:

Input: candies = 10, num_people = 3
Output: [5,2,3]
Explanation: 
On the first turn, ans[0] += 1, and the array is [1,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0].
On the third turn, ans[2] += 3, and the array is [1,2,3].
On the fourth turn, ans[0] += 4, and the final array is [5,2,3].

 

Constraints:

  • 1 <= candies <= 10^9
  • 1 <= num_people <= 1000

解法:

使用give%num_people确定当前的人的位置,min(candies, give+1)是每次分的糖果数量;
将每次分糖果数量增加1(give+=1,candies-=give),直到用完糖果(while candies>0)。

    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        people = num_people * [0]
        give = 0
        while candies > 0:
            people[give % num_people] += min(candies, give + 1)
            give += 1
            candies -= give
        return people

Time: O(sqrt(candies)), space: O(num_people).

Runtime: 48 ms, faster than 23.90% of Python3 online submissions for Distribute Candies to People.
Memory Usage: 14.1 MB, less than 19.03% of Python3 online submissions for Distribute Candies to People.

 

以上是关于LeetCodeMathdistribute candies to people分糖问题的主要内容,如果未能解决你的问题,请参考以下文章