1103. Distribute Candies to People(python 3)

Description:

We distribute some number of candies, to a row of n = num_people people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.
Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
Return an array (of length num_people and sum candies) that represents the final distribution of candies.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distribute-candies-to-people
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 分糖果。递增数列。第一个人1个,第二个人2个...若人数有限,遍历一遍回到第一个人继续往下增加,直到余下糖果给最后一个人无。

  • QAQ 看教程才会暴力解题

class Solution:
    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        ans = [0] * num_people
        n = 0
        while candies != 0:
            ans[n % num_people] += min(n+1, candies)
            candies -= min(n+1, candies)
            n += 1
        return ans
  • 要学会灵活使用条件以及 min,max这种语句。

  • leetcode 比较项目里还包括执行用时及执行复杂度。加油!

你可能感兴趣的:(1103. Distribute Candies to People(python 3))