校园网站建设材料,首饰网站建设策划案,青岛营销网站建设,网站验收技术指标方法一 个人方法#xff1a;
有多少人就创建多大的数组并把数组的所有元素初始化为0#xff0c;只要还有糖果#xff0c;就循环给数组从头到尾添加糖果#xff0c;每次分的糖果数递增1#xff0c;最后可能刚好分完也可能不够#xff0c;不够就还剩多少给多少。
var dis…
方法一 个人方法
有多少人就创建多大的数组并把数组的所有元素初始化为0只要还有糖果就循环给数组从头到尾添加糖果每次分的糖果数递增1最后可能刚好分完也可能不够不够就还剩多少给多少。
var distributeCandies function(candies, num_people) {var res new Array(num_people).fill(0)var i0while(candies0){if(candies-i-10){res[i%num_people]i1candies-i1}else{res[i%num_people]candiescandies0}i}return res
};
消耗时间和内存情况 方法二 数学公式 详细公式推导过程
作者力扣官方题解 链接leetcode 1103 题解
var distributeCandies function(candies, num_people) {let n num_people let p Math.floor((2 * candies 0.25)**0.5 - 0.5)let r Math.floor(candies - (p 1) * p * 0.5)let res new Array(n).fill(0)let rows Math.floor(p/n)let cols p%n for (let i 0; i n; i) {res[i] (i1)*rows Math.floor(rows * (rows - 1) * 0.5) * n if(icols) res[i] i1rows*n }res[cols] r return res};
消耗时间和内存情况