1103. 分糖果 II
我的解法:模拟整个分配糖果的过程:时间复杂度为 O ( m a x ( c a n d i e s , N ) ) O(max(\sqrt{candies}, N)) O(max(candies,N)),N是人数。
class Solution {
public int[] distributeCandies(int candies, int num_people) {
int[] getCandy = new int[num_people];
int times = 0;
while(candies > 0){
for(int i = 0; i < num_people; i++){
int temp = times + (i + 1); // 本轮该孩子预计能得到的糖果数
if(candies - temp > 0){
// 还够,那么给孩子需要的,并且更新当前糖果数
getCandy[i] += temp;
candies -= temp;
}
else{
// 如果糖果数量不够当前孩子的or刚好仅够,那么全部给该孩子,直接返回
getCandy[i] += candies;
return getCandy;