Rabbits In Forest


  • 0

    Click here to see the full article post


  • 0
    G
        answers.sort()
        i,s=0,0
        while i<len(answers):
            s=s+(answers[i]+1)*math.ceil(answers.count(answers[i])/(answers[i]+1))
            i=i+answers.count(answers[i])
        return s

  • 0
    I
    public int numRabbits(int[] answers) {
            int a[]= new int[1000];
            for(int i=0;i<answers.length;i++){
                a[answers[i]]++;
            }
            int total=a[0];
            for(int i=1;i<a.length;i++){
                total+= a[i] != 0 && a[i]%(i+1)>0? (a[i] +((i+1)-(a[i]%(i+1)))):a[i];
            }
            return total;
       }
    

  • 0
    L

    i think there is a solution based on sorted array:

    class Solution {
        public int numRabbits(int[] answers) {
            if(answers.length==0)return 0;
                    
            java.util.Arrays.sort(answers);
            int pre=answers[0],cur = pre,sum=0;
            for(int i=1;i<=answers.length;i++){
                if(i==answers.length){
                    sum+=pre+1;
                }else{
                    if(answers[i]==pre){
                        if(--cur<0){
                            cur = answers[i];
                            sum+=pre+1;
                        }
                    }else{
                        sum+=pre+1;
                        cur = answers[i];
                    }
                    
                    pre = answers[i];
                }
            }
            return sum;
        }
    }
    

  • 0
    D

    what is the significance of sending the complement of count[k] inside floorMod on line 8, tried reading the oracle docs on floorMod operation, it made little to no sense.


  • 0

    @dejokz floorMod(k, m) is just the nonnegative value of k % m.
    If there are say 2 rabbits that say 9, there are 10 total in that group, so we want -2 % 10 = 8 more.


  • 0
    J

    what if input is [1, 1, 1, 1], would there only be two rabbits since the first two and last two might be referring to one another? The code above gives 4 as answer


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.