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:
The length of the given array is in range [2, 10,000], and will be even.
The number in given array is in range [-100,000, 100,000].

Solution:

思路:
如果总共有n个糖,平均分给两个人,每人得到n/2块糖,那么能拿到的最大的糖的种类数也就是n/2种,不可能再多,只可能再少。那么我们要做的就是统计出总共的糖的种类数,如果糖的种类数小于n/2,说明拿不到n/2种糖,最多能拿到的种类数数就是当前糖的总种类数
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

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

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,523评论 0 23
  • 四、石窟摩崖造像 1.石窟 (1)概述 ①来源及发展中国的石窟来源于印度的石窟寺,约在南北朝时期传入我国,鼎盛时期...
    槑槑啊阅读 3,073评论 0 1
  • 我们家不再养狗,从我记事以来,我们家养过两只狗,一只被人偷走,一只被毒死,也许是因为受不了狗狗死亡的打击,我的妈妈...
    雪鲸呀阅读 1,805评论 2 2
  • 有人觉得,秋夕只不过是秋天的日落罢了,错!在我眼中它是有生命力的斜阳,我给它致词叫:秋之斜阳。富含了美丽之景。 如...
    受益好民阅读 2,372评论 3 1
  • [ Purpose ] We implemented a distributed grep system that...
    陈十十阅读 1,400评论 2 0

友情链接更多精彩内容