Java solution beats 99.07%


  • 2

    Based on Bucket Sort:

    
        public int distributeCandies(int[] candies) {
            int[] b = new int[200001];
            int nonEmptyBucketNo = 0;
            for (int i : candies) if (b[i + 100000]++ == 0) nonEmptyBucketNo++;
            return nonEmptyBucketNo <= candies.length / 2 ? nonEmptyBucketNo : candies.length / 2;
        }
    

  • 0
    H

    @vegito2002 said in Java solution beats 99.07%:

    int[] b = new int[200001];
    int nonEmptyBucketNo = 0;
    for (int i : candies) if (b[i + 100000]++ == 0) nonEmptyBucketNo++;
    return nonEmptyBucketNo <= candies.length / 2 ? nonEmptyBucketNo : candies.length / 2;

    Even faster to use boolean array:

    public class Solution {
        public int distributeCandies(int[] candies) {
             boolean[] b = new boolean[200001];
             int nonEmptyBucketNo = 0;
             for (int i : candies) if (b[i + 100000] == false) {nonEmptyBucketNo++; b[i+100000] = true;}
             return nonEmptyBucketNo <= candies.length / 2 ? nonEmptyBucketNo : candies.length / 2;        
        }
    }
    

Log in to reply
 

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