1. 程式人生 > 其它 >#力扣 LeetCode1103. 分糖果 II @FDDLC

#力扣 LeetCode1103. 分糖果 II @FDDLC

技術標籤:演算法&資料結構

題目描述:

https://leetcode-cn.com/problems/distribute-candies-to-people/

Java程式碼:

class Solution {
    public int[] distributeCandies(int candies, int num_people) {
        int[] ans=new int[num_people];
        for(int i=0,j=1;;i=(i+1)%num_people,j++){
            if(candies>=j){
                ans[i]+=j;
                candies-=j;
            }else{
                ans[i]+=candies;
                return ans;
            }
        }
    }
}

Java程式碼二:

class Solution {
    public int[] distributeCandies(int cds, int pls) {
        int[] ans=new int[pls];
        int n=(int)(Math.sqrt(2.0*cds)-0.5+0.001),row=n/pls,several=n%pls;
        for(int i=0,v=row*(row-1)/2*pls+row;i<pls;i++,v+=row)ans[i]=v;
        for(int i=0,v=pls*row+1;i<several;i++,v++)ans[i]+=v;
        ans[n%pls]+=cds-(1+n)*n/2; //f(n)的下一個為f(n+1),這裡為ans[n%pls],因為f(1)=ans[0]
        return ans;
    }
}