zoukankan      html  css  js  c++  java
  • leetcode算法: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].

    这道题是说 给我们一个数组 [1,1,2,2,3,3]
    每个数字代表一种类型的糖果,这个数组也就是有两颗1类型糖果 两个2类型糖果 两个3类型糖果

    现在要男孩和女孩数量上等分这些糖果,问女孩最多能得到多少种类的糖果


    思想就是:
    num1 = 总数量/2 num2 = 糖果种类数
    如果num1 更多,那女孩一定能每种糖果得到一个以上,所以num2是答案
    如果num2更大,那么女孩就不可能每种糖果都能拿到一个,所以num1就是答案

    总数量就是数组的长度,糖果种类数就是把数组去重,看有多少个数字,可以用集合来做,
    我的python代码:

     1 class Solution(object):
     2     def distributeCandies(self, candies):
     3         """
     4         :type candies: List[int]
     5         :rtype: int
     6         """
     7         kinds = len( set(candies) )
     8         nums = len(candies)/2
     9         if kinds< nums:
    10             return kinds
    11         else:
    12             return nums
    13 
    14 
    15 if __name__ == '__main__':
    16     s = Solution()
    17     res = s.distributeCandies([1,1,1,1,2,2,2,3,3,3])
    18     print(res)
  • 相关阅读:
    AOP编程之cglib动态代理:进阶一
    16-python基础5-文件读写操作
    13-python基础2-条件和循环
    12-python基础1-python概述
    11-linux基础八-正则表达式
    07-linux基础四-系统监控和硬盘分区
    06-linux基础三-文件操作和系统启动流程
    05-linux基础二-用户和权限操作
    04-linux基础一概述和简单命令
    03-网络通信原理
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501745.html
Copyright © 2011-2022 走看看