每日一题——LeetCode1103.分糖果 ||

方法一 个人方法:

有多少人就创建多大的数组并把数组的所有元素初始化为0,只要还有糖果,就循环给数组从头到尾添加糖果,每次分的糖果数递增1,最后可能刚好分完也可能不够,不够就还剩多少给多少。

var distributeCandies = function(candies, num_people) {
    var res = new Array(num_people).fill(0)
    var i=0
    while(candies>0){
        if(candies-i-1>=0){
            res[i%num_people]+=i+1
            candies-=i+1
        }else{
            res[i%num_people]+=candies
            candies=0
        }
        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] = (i+1)*rows + Math.floor(rows * (rows - 1) * 0.5) * n 
        if(i<cols) res[i] += i+1+rows*n 
    }
    res[cols] += r 
    return res

};

消耗时间和内存情况:

扫描二维码关注公众号,回复: 17370083 查看本文章

 

猜你喜欢

转载自blog.csdn.net/weixin_52878347/article/details/135536368