码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】【Math】distribute candies to people分糖问题

时间:2020-06-25 17:22:33      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:leetcode   sqrt   memory   style   增加   ons   lis   返回   self   

题目:

共有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.

 

【LeetCode】【Math】distribute candies to people分糖问题

标签:leetcode   sqrt   memory   style   增加   ons   lis   返回   self   

原文地址:https://www.cnblogs.com/jialinliu/p/13192069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!