Distribute Candies

来源:互联网 发布:认知计算与人工智能pdf 编辑:程序博客网 时间:2024/06/17 10:58

题目大意:

每个数字代表一种糖果。共偶数个糖果,平分给弟弟妹妹,如何让妹妹获得最多种类的糖果?

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: 3Explanation: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: 2Explanation: 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. 

解题思路:

  • 比较糖果种类和半数糖果的大小,如果半数糖果大则返回糖果种类,否则返回半数糖果。

代码如下:

public class Solution {    public int distributeCandies(int[] candies) {        Set dif = new HashSet();        for(Integer i:candies){            dif.add(i);        }        return (dif.size()>candies.length/2 ? candies.length/2 : dif.size());    }}
0 0
原创粉丝点击