LeetCode

来源:互联网 发布:vb log 编辑:程序博客网 时间:2024/05/16 12:15

题目链接:575. Distribute Candies


题目大意:给你一个长度为偶数的整数数组,这个数组中的不同的数字代表着不同种类的糖果。每种数字代表一个相应的糖果。现在把这些糖果平均分给哥哥和妹妹,返回妹妹能得到的最大种类的糖果数量(也就是不同数字最多的一种分类方式下的那个最大值)


这道题目思路也很简单,假设糖果总数为n,假设糖果种类大于n/2,这样妹妹最多得到n/2种,如果糖果种类小于n/2,这样妹妹得到的最大值就是糖果的种类数目。


def distributeCandies(self, candies):    l = len(set(candies))    if l <= (len(candies) // 2):        return l    else:        return (len(candies) // 2)

一行代码的解法:

def distributeCandies(self, candies):    return min(len(candies) // 2, len(set(candies)))

尽管题目明确了数组长度是偶数,但是还是建议大家使用//整除。

以上。

原创粉丝点击