zoukankan      html  css  js  c++  java
  • 575. 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. 

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 查看set中有几个数,只要用.size()即可

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    hashtable hashset的key具有单一性 不能重复

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    hashset的key具有单一性 不能重复,对应糖果的种类也是

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int distributeCandies(int[] candies) {
            //cc
            if (candies == null || candies.length == 0) {
                return 0;
            }
            
            //ini
            Set kinds = new HashSet();
            
            //for
            for (int candy : candies) {
                kinds.add(candy);
            }
            
            //return :
            return (candies.length / 2) > kinds.size() ? kinds.size() : (candies.length / 2);
        }
    }
    View Code
  • 相关阅读:
    google glog 使用方法
    LIBRARY_PATH和LD_LIBRARY_PATH环境变量的区别
    c++ ‘nullptr’ 在此作用域中尚未声明
    Impala 使用的端口
    忽略“Signal: SIGSEGV (Segmentation fault)”
    查看python脚本的运行pid,让python脚本后台运行
    阿里云主机运行速度慢的解决办法
    在Git.oschina.net中配置TortoiseGit使用sshkey,无需输入账号和密码
    抓取国家的学校编码数据
    CAS统一登录认证好文汇集贴
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8931800.html
Copyright © 2011-2022 走看看