[Power button - small daily practice] 1103. minute Candy II (python)

1103. minute Candy II: Cruncher, sub-candy.

Subject description:

We bought some candy candies, they are going to give queued n = num_people two children.

A child to the first confectionery, the second two children, and so on, until the last child to n pieces of candy.

Then, we go back to the starting point of the team, to the first pieces of candy children n + 1, n + 2 second child stars, and so on, until the last child to 2 * n pieces of candy.

Repeat the process (and more each time than the last given a candy, when the team arrived at the end from the beginning starting point for the team again) until we finish all the sub-candy. Note that even if the rest is not in our hands the number of candy (candy before issuing more than once), these candies will be distributed to all current children.

Returns an array of NUM_PEOPLE length, and for the elements of the candies to represent the case of candies final distribution (i.e. ANS [i] represents the number of i-th candy assigned to children).

Example 1:

Input: candies = 7, num_people = 4
Output: [1,2,3,1]
Explanation:
first, ans [0] + = 1 , the array becomes [1,0,0,0].
Second, ans [1] + = 2 , the array becomes [1,2,0,0].
Third, ans [2] + = 3 , the array becomes [1,2,3,0].
Fourth, ans [3] + = 1 ( because the only one candy), the final array becomes [1,2,3,1].

Example 2:

Input: candies = 10, num_people = 3
Output: [5,2,3]
Explanation:
first, ans [0] + = 1 , the array becomes [1,0,0].
Second, ans [1] + = 2 , the array becomes [1,2,0].
Third, ans [2] + = 3 , the array becomes [2,3].
Fourth, ans [0] + = 4 , the final array becomes [5,2,3].

 

prompt:

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

Python代码实现:

class Solution:
    
    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        
        ans = num_people*[0]    # 创建长度为num_people的空列表
        j = 1
        while candies!=0:
            for i in range(num_people):
                if candies<=j:
                    ans[i] += candies
                    candies=0
                    break
                else:
                    ans[i] += j
                candies = candies - j
                j += 1

        return ans

 

Published 44 original articles · won praise 5 · Views 4474

Guess you like

Origin blog.csdn.net/ljb0077/article/details/104672437