zoukankan      html  css  js  c++  java
  • 分糖果

    此博客链接:https://www.cnblogs.com/ping2yingshi/p/14051225.html

    分糖果

    题目链接:https://leetcode-cn.com/problems/distribute-candies/

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

    示例 1:

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

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

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

    题解

    思路:使用哈希表存储不同数字的个数,数字为key,数字的个数为value,取数字个数少的数字作为分给妹妹的糖果。

    方法:

              1.建立哈希表。

               2.把value的值取出进行排序(从小到大)。

               3.对value的值相加,直到加到给的数字个数的一半为止。

    代码

    class Solution {
        public int distributeCandies(int[] candyType) {
             Map <Integer,Integer> map=new HashMap();
             //建立哈希表
             for(int tem:candyType)
             {
                 Integer temp=map.get(tem);
                 if(temp!=null)
                   map.put(tem,temp++);
                else
                   map.put(tem,1);
             }
             int count []=new int [map.size()];
             for(int i=0;i<map.size();i++)
             {
                 count[i]=map.get(i);
             }
             //排序,冒泡排序
             for(int i=0;i<map.size()-1;i++)
                 for(int j=i+1;j<map.size();i++)
                {
                    if(count[i]>count[j])
                    {
                        int temp=count[i];
                        count[i]=count[j];
                        count[j]=temp;
                    }
                    
                }
                int result=0;//保存结果
                int sum=0;//计算糖果数
                for(int i=0;i<map.size();i++)
                {
                    if(sum<candyType.length/2)
                    {
                        sum+=map.get(i);
                        result++;
                    }
                }
                return result;
    
    
    
        }
    }

    代码有问题,说数组越界,但是我没有发现越界。

    出来混总是要还的
  • 相关阅读:
    codeforces 407B Long Path
    CodeForces 489C Given Length and Sum of Digits...
    hacker cup 2015 Round 1 解题报告
    hacker cup 2015 资格赛
    Codeforces 486(#277 Div 2) 解题报告
    POJ 3468 A Simple Problem with Integers splay
    Codeforces 484(#276 Div 1) D Kindergarten DP
    求平均值问题201308031210.txt
    I love this game201308022009.txt
    QQ
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/14051225.html
Copyright © 2011-2022 走看看