LeetCode.575 Distribute Candies

来源:互联网 发布:mac mini 内置扬声器 编辑:程序博客网 时间:2024/06/05 05:27

题目:

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. 

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].
分析1(HashSet实现):

class Solution {    public int distributeCandies(int[] candies) {        //给定偶数长度的数组,其中不同元素表示不同种类的糖果,现在需要分配给妹妹和哥哥糖果各一半        //返回妹妹获取最多种类的糖果数量        //思路:使用Set来判断糖果种类        //注意:妹妹最多获取糖果数量为数组的一半,即所有糖果均不同                //初始化        HashSet<Integer> set=new HashSet<Integer>();        int diff=0;        int res=0;        for(int i=0;i<candies.length;i++){            if(set.add(candies[i])){                diff++;            }        }                if(diff>candies.length/2){            //说明有超过一半的不同            res=candies.length/2;        }else{            res=diff;        }        return res;    }}

分析2(数组实现-推荐):

class Solution {    public int distributeCandies(int[] candies) {        //给定偶数长度的数组,其中不同元素表示不同种类的糖果,现在需要分配给妹妹和哥哥糖果各一半        //返回妹妹获取最多种类的糖果数量        //思路:使用数组来存储种类        //注意:妹妹最多获取糖果数量为数组的一半,即所有糖果均不同                //确保数组所有元素都从0开始,则将正负范围(-100000,100000)叠加,这里不确定数的大小,所有保证元素范围作为标识位        boolean [] flag=new boolean[200001];        int diff=0;        for(int i=0;i<candies.length&&diff<candies.length/2;i++){            //当判断到种类不同的有一半长度即可以停止判断            if(!flag[candies[i]+100000]){                diff++;                //标识位置true                flag[candies[i]+100000]=true;            }        }                return Math.min(diff,candies.length/2);    }}


原创粉丝点击