★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wmpzhraj-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
Example 1:github
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:微信
給定一個偶數長度的數組,其中不一樣的數字表明着不一樣種類的糖果,每個數字表明一個糖果。你須要把這些糖果平均分給一個弟弟和一個妹妹。返回妹妹能夠得到的最大糖果的種類數。this
示例 1:spa
輸入: candies = [1,1,2,2,3,3] 輸出: 3 解析: 一共有三種種類的糖果,每一種都有兩個。 最優分配方案:妹妹得到[1,2,3],弟弟也得到[1,2,3]。這樣使妹妹得到糖果的種類數最多。
示例 2 :code
輸入: candies = [1,1,2,3] 輸出: 2 解析: 妹妹得到糖果[2,3],弟弟得到糖果[1,1],妹妹有兩種不一樣的糖果,弟弟只有一種。這樣使得妹妹能夠得到的糖果種類數最多。
注意:htm
380msblog
1 class Solution { 2 func distributeCandies(_ candies: [Int]) -> Int { 3 let cSet:Set<Int> = Set(candies) 4 return min(cSet.count,candies.count/2) 5 } 6 }
400ms
1 class Solution { 2 func distributeCandies(_ candies: [Int]) -> Int { 3 //Set存儲相同類型的不一樣值,沒有定義的順序。 4 var kind:Set<Int> = Set<Int>() 5 for i in candies 6 { 7 kind.insert(i) 8 } 9 return min(candies.count / 2, kind.count) 10 } 11 }
404ms
1 class Solution { 2 func distributeCandies(_ candies: [Int]) -> Int { 3 let dict = candies.reduce(into: [:]) { $0[$1, default: 0] += 1 } 4 return min(dict.keys.count, candies.count/2) 5 } 6 }
1552ms
1 class Solution { 2 func distributeCandies(_ candies: [Int]) -> Int { 3 var hash = Set<Int>() 4 5 for i in 0...candies.count - 1 { 6 if hash.count == (candies.count / 2) { 7 return candies.count / 2 8 } 9 hash.insert(candies[i]) 10 } 11 12 return hash.count 13 } 14 }