leetcode的每日一题更新(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.
意思大概就是两兄妹分糖果,给一个数组,一个数字代表一种糖果,平均分,问最多能分到几种糖果
思路:刚开始想的太复杂,理不清那种,后面仔细看了以下题目,其实很简单,就是如果数组的长度的一半超过糖果的种类,那就是重复的有很多,可以分到全部的种类,如果数组的长度的一般没有超过糖果的种类,说明重复的少,只要返回数组长度的一半就可以了,用hashset解决计算糖果种类。
代码:

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

看了以下solution和我的基本一样,也是用hashset来算糖果种类

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();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容