[Swift]LeetCode575. 分糖果 | Distribute Candies

[Swift]LeetCode575. 分糖果 | Distribute Candies,第1张

概述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

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,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,3] and the brother has candIEs [1,3],too. The sister has three different kinds of candIEs. 

 Example 2:

input: candIEs = [1,3]Output: 2Explanation: For example,the sister has candIEs [2,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].

给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。

示例 1:

输入: candIEs = [1,3]输出: 3解析: 一共有三种种类的糖果,每一种都有两个。     最优分配方案:妹妹获得[1,弟弟也获得[1,3]。这样使妹妹获得糖果的种类数最多。

示例 2 :

输入: candIEs = [1,3]输出: 2解析: 妹妹获得糖果[2,弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。

注意:

数组的长度为[2,000],并且确定为偶数。 数组中数字的大小在范围[-100,000]内。

 380ms

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.count13     }14 }
总结

以上是内存溢出为你收集整理的[Swift]LeetCode575. 分糖果 | Distribute Candies全部内容,希望文章能够帮你解决[Swift]LeetCode575. 分糖果 | Distribute Candies所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1023436.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存