# Java Solution, 3 lines, HashSet

• Thanks @wmcalyj , modified to use HashSet.

``````public class Solution {
public int distributeCandies(int[] candies) {
Set<Integer> kinds = new HashSet<>();
for (int candy : candies) kinds.add(candy);
return kinds.size() >= candies.length / 2 ? candies.length / 2 : kinds.size();
}
}
``````

• Good solution! Thanks! Although I think you don't really need HashMap here. All you care about is how many kinds of candies you have here, not how many candies for each kind.
Here is my solution:

``````public int distributeCandies(int[] candies) {
int total = candies.length;
Set<Integer> kinds = new HashSet<Integer>();
for (int i = 0; i < total; i++) {
}
if (kinds.size() > total / 2) {
} else {
return kinds.size();
}
}
``````

• It also can be done in one line with Stream API

``````return Math.min(candies.length / 2, Arrays.stream(candies).boxed().collect(Collectors.toSet()).size());
``````

• Same idea.

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

• This post is deleted!

• @wmcalyj HashSet run with HashMap both of them are OK

Here is my solution:

``````public class Solution {
public int distributeCandies(int[] candies) {
int len=candies.length;

Map<Integer,Integer> hashK=new HashMap<>(1024);

for(int i=0;i<len;i++){
if(!hashK.containsKey(candies[i])){
hashK.put(candies[i],i);
}
}

int kindSize=hashK.size();

return kindSize>=len/2?len/2:kindSize;
}
}
``````

• In the loop, if the set's size reaches length/2, you could do an early termination which improves a bit performance here. :)

• @petery0621 Nice Idea. Agreed

• Same idea.

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

• Wow, very neat! I used a count instead of size(), how foolish I am lol.

@shawngao By the way, your solution could be optimized if you check `set.size()` inside your `for` loop. Since you can break your for loop and return the result if `kinds.size() == candies.length / 2`. You don't need to continue adding to your set. :)

• @wmcalyj

I like the idea for early termination!

• public class Solution {
public int distributeCandies(int[] candies) {
int n=candies.length/2;
Set sister=new HashSet();
int i=0;
while(n>0&&i<candies.length){
n--;
}

``````    }
return (sister.size());
}
``````

}

• Java 8 solution

``````public class Solution {
public int distributeCandies(int[] candies) {
return Math.min(candies.length / 2, ((int) Arrays.stream(candies).distinct().count()));
}
}
``````

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