# LeetCode.575.Distribute Candies 分糖果

## 题目描述

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
Example 1:

Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
The sister has three different kinds of candies.

Example 2:

Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
The sister has two different kinds of candies, the brother has only one kind of candies.

Note:

1. The length of the given array is in range [2, 10,000], and will be even.
2. The number in given array is in range [-100,000, 100,000].

## 解题过程

import java.util.HashMap;
import java.util.Map;

class Solution {
public int distributeCandies(int[] candies) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<candies.length; i++){
map.put(candies[i], i);
}
if(map.size() >= candies.length/2){
return candies.length/2;
}else {
return map.size();
}
}
}

public class DistributeCandies {
public static void main(String[] args){
Solution solution = new Solution();
int[] candies = {1,1,1,1,2,2,2,3,3,3};
System.out.println(solution.distributeCandies(candies));
}
}

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();
}
}

public class Solution {
public int distributeCandies(int[] candies) {
return Math.min(candies.length / 2, IntStream.of(candies).boxed().collect(Collectors.toSet()).size());
}
}

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

## GitHub代码

algorithms/leetcode/leetcode/_575_DistributeCandies.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_575_DistributeCandies.java

634

#### 页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent: