Java hashset solution


  • 2
    public int distributeCandies(int[] candies) {
        Set<Integer> set = new HashSet<>();
        for(Integer candie : candies) {
            set.add(candie);
            if(set.size() == candies.length/2) return set.size();
        }
        return Math.min(set.size(), candies.length/2);
    }

  • 1
    Y

    I didn't return in the for loop just to make the code look nicer.
    Performance wise, yours is better!

    public int distributeCandies(int[] candies) {
        Set<Integer> set = new HashSet<>();
        for (int c : candies) {
            set.add(c);
        }
        return Math.min(set.size(), candies.length / 2);
     }
    

  • 3
    I

    The last return may be can simply return set.size();


Log in to reply
 

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