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塊糖,那么能拿到的最大的糖的種類數(shù)也就是n/2種,不可能再多,只可能再少。那么我們要做的就是統(tǒng)計出總共的糖的種類數(shù),如果糖的種類數(shù)小于n/2,說明拿不到n/2種糖,最多能拿到的種類數(shù)數(shù)就是當前糖的總種類數(shù)
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();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,036評論 0 23
  • 四、石窟摩崖造像 1.石窟 (1)概述 ①來源及發(fā)展中國的石窟來源于印度的石窟寺,約在南北朝時期傳入我國,鼎盛時期...
    槑槑啊閱讀 468評論 0 1
  • 我們家不再養(yǎng)狗,從我記事以來,我們家養(yǎng)過兩只狗,一只被人偷走,一只被毒死,也許是因為受不了狗狗死亡的打擊,我的媽媽...
    雪鯨呀閱讀 283評論 2 2
  • 有人覺得,秋夕只不過是秋天的日落罷了,錯!在我眼中它是有生命力的斜陽,我給它致詞叫:秋之斜陽。富含了美麗之景。 如...
    受益好民閱讀 331評論 3 1
  • [ Purpose ] We implemented a distributed grep system that...
    陳十十閱讀 199評論 2 0

友情鏈接更多精彩內(nèi)容