标签:java str lse ble 分糖果 小朋友 for 朋友 public
排排坐,分糖果。
我们买了一些糖果 candies
,打算把它们分给排好队的 n = num_people
个小朋友。
给第一个小朋友 1 颗糖果,第二个小朋友 2 颗,依此类推,直到给最后一个小朋友 n
颗糖果。
然后,我们再回到队伍的起点,给第一个小朋友 n + 1
颗糖果,第二个小朋友 n + 2
颗,依此类推,直到给最后一个小朋友 2 * n
颗糖果。
重复上述过程(每次都比上一次多给出一颗糖果,当到达队伍终点后再次从队伍起点开始),直到我们分完所有的糖果。注意,就算我们手中的剩下糖果数不够(不比前一次发出的糖果多),这些糖果也会全部发给当前的小朋友。
返回一个长度为 num_people
、元素之和为 candies
的数组,以表示糖果的最终分发情况(即 ans[i]
表示第 i
个小朋友分到的糖果数)。
通过等差数列求出被完整分配的轮数turns
,直接计算出前turns
轮每个小朋友获得的糖果数,然后直接处理最后一轮。
代码如下:
class Solution {
public int[] distributeCandies(int candies, int num_people) {
int[] results = new int[num_people];
int sum_of_all_turns = num_people * (num_people + 1) / 2;
if (candies < sum_of_all_turns) {
for (int i = 0; i < num_people; i++) {
if (candies < i + 1) {
results[i] += candies;
break;
}
else {
results[i] += i + 1;
candies -= i + 1;
}
}
return results;
}
int turns = 1;
int square = ((2 * turns + 1) * num_people * num_people + num_people) / 2;
while (sum_of_all_turns + square < candies) {
sum_of_all_turns += square;
turns++;
square = ((2 * turns + 1) * num_people * num_people + num_people) / 2;
}
for (int i = 0; i < num_people; i++) {
results[i] += turns * (turns - 1) * num_people / 2 + turns * (i + 1);
}
candies -= sum_of_all_turns;
for (int i = 0; i < num_people; i++) {
if (candies < turns * num_people + (i + 1)) {
results[i] += candies;
return results;
}
else {
results[i] += turns * num_people + (i + 1);
candies -= turns * num_people + (i + 1);
}
}
return results;
}
}
直接利用每份礼物的数量和完整分配的礼物数量的关系求出一共完整分配了p
次。直接计算出前p
次分配后每个小朋友获得的糖果数,然后将剩余的糖果分配给第p % n + 1
个小朋友。
class Solution {
public int[] distributeCandies(int candies, int num_people) {
int n = num_people;
// how many people received complete gifts
int p = (int)(Math.sqrt(2 * candies + 0.25) - 0.5);
int remaining = (int)(candies - (p + 1) * p * 0.5);
int rows = p / n, cols = p % n;
int[] d = new int[n];
for(int i = 0; i < n; ++i) {
// complete rows
d[i] = (i + 1) * rows + (int)(rows * (rows - 1) * 0.5) * n;
// cols in the last row
if (i < cols) d[i] += i + 1 + rows * n;
}
// remaining candies
d[cols] += remaining;
return d;
}
}
//作者:LeetCode-Solution
//链接:https://leetcode-cn.com/problems/distribute-candies-to-people/solution/fen-tang-guo-ii-by-leetcode-solution/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:java str lse ble 分糖果 小朋友 for 朋友 public
原文地址:https://www.cnblogs.com/aries99c/p/12419362.html