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)
  • 相关阅读:
    自定义控件类
    初探ListView和Adapter
    探究android控件及布局
    页面布局之一边固定一边自适应
    cavans 文字换行
    移动开发01 页面取消横向滚动条
    移动端rem,scale动态设置
    map,area标签
    css3属性——border-radius用法
    z-index要同级比较,absolute包含块外有overflow-hidden
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501745.html
Copyright © 2011-2022 走看看