[LeetCode] 1103. Distribute Candies to People 分糖果

topic:


 Ideas:

This idea is the beginning of a question in accordance with the process step by step points down, be violent methods, the official explanations have calculated using the arithmetic sequence of

Here only record your own way of solving violence

Only consider the number of candy each allocation, the allocation of the number of candy 1,2,3,4,5, ..., is incremented by 1

Taking into account the distribution of the number of rounds, you can use  i% num_people  to obtain first a few people should be assigned to the i-th

Finally, note that, if the number is less than the current number of confectionery candy should distribution, the current candy all given, that is, to determine the remaining number of confectionery  candies  with the present number of allocated candy  I + . 1  size, small who who assigned

Code:

class Solution {
public:
    vector<int> distributeCandies(int candies, int num_people) {
        // vector<int> res(num_people, 0);
        // int i=1;
        // for(int k=0; candies>=i+k*num_people; k++){
        //     while(i <= num_people){
        //         if(candies<i+k*num_people){
        //             res[i-1] += candies;
        //             candies = 0;
        //             break;
        //         }
        //         res[i-1] += i+k*num_people;
        //         candies -= i+k*num_people;
        //         i++;
        //     }
        //     i=1;
        // }
        // if(candies) res[0] += candies;
        // return res;
        vector<int> ans(num_people);    // 初始元素为0
        int i=0;
        while(candies!=0){
            ans[i % num_people] += min(candies, i+1);
            candies -= min(candies, i+1);
            i++;
        }
        return ans;
    }
};

The annotated code their own ideas, although the same complexity, see the solution to a problem only to find themselves fuss, do not understand the subject thoroughly

Guess you like

Origin www.cnblogs.com/ech2o/p/12419281.html