LeetCode 1103. Distribute Candies to People (分糖果 II)

时间:2022-05-29 06:16:30

题目标签:Math

  题目让我们分发糖果,分的糖果从1 开始依次增加,直到分完。

  for loop可以计数糖果的数量,直到糖果发完。但是还是要遍历array 给people 发糖,这里要用到 index = (本轮分糖果的量 % people 的人数)糖果的数量从0 开始计数,这样的话,index 就会一直重复遍历 array,具体看code。

Java Solution:

Runtime:  1ms, faster than 90.53%

Memory Usage: 33.8 MB, less than 100.00%

完成日期:07/15/2019

关键点:利用%重复遍历array

class Solution {
public int[] distributeCandies(int candies, int num_people) {
int[] people = new int[num_people]; for(int give = 0; candies > 0; candies -= give) {
people[give % num_people] += Math.min(candies, ++give);
} return people;
}
}

参考资料:LeetCode discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/