zoukankan      html  css  js  c++  java
  • LeetCode

    题目链接地址:

      https://leetcode.com/problems/distribute-candies/description/

    题目大意:

      给定一个偶数长度的整数数组,数组中的不同数字代表不同种类的糖果。每一个数字意味着相应的一个糖果。你需要把这些糖果均匀地分配给弟弟和妹妹。返回姐姐能得到的糖果的最大数量。

    样例1

    输入:糖果= [ 1,1,2,2,3,3 ]
    输出:3
    解释:
    有三种不同的糖果(1, 2和3),每种糖果两种。
    优化配置:姐姐有糖果[1,2,3],弟弟有糖果[1,2,3],也。
    姐姐有三种不同的糖果。

    样例2

    输入:糖果= [ 1,1,2,3 ]
    输出:2
    说明:例如,妹妹有糖果(2,3),而兄弟有糖果(1,1)。
    姐姐有两种不同的糖果,弟弟只有一种糖果。

    算法思路

    第一种:先对数组排序,那么同种糖果归类到了一起。只需遍历数组,每种糖果取一种,直到数量达到一半。
    第二种:直接将每种糖果存入set,则可获得所有糖果的种类,若种类大于一半,则返回数组长度的一半(因为妹妹最多获得一半数量糖果)

    java代码实现

    class Solution {
        public int distributeCandies(int[] candies) {
            Set<Integer> kinds = new HashSet<>();
            for (int candy : candies) kinds.add(candy);
            return kinds.size() >= candies.length / 2 ? candies.length / 2 : kinds.size();
        }
    }
    
    public class MainClass {
        public static int[] stringToIntegerArray(String input) {
            input = input.trim();
            input = input.substring(1, input.length() - 1);
            if (input.length() == 0) {
              return new int[0];
            }
        
            String[] parts = input.split(",");
            int[] output = new int[parts.length];
            for(int index = 0; index < parts.length; index++) {
                String part = parts[index].trim();
                output[index] = Integer.parseInt(part);
            }
            return output;
        }
        
        public static void main(String[] args) throws IOException {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String line;
            while ((line = in.readLine()) != null) {
                int[] candies = stringToIntegerArray(line);
                
                int ret = new Solution().distributeCandies(candies);
                
                String out = String.valueOf(ret);
                
                System.out.print(out);
            }
        }
    }
    

      

  • 相关阅读:
    [PKUSC2018]星际穿越——可持久化线段树+DP
    BZOJ2863[SHOI2012]魔法树——树链剖分+线段树
    BZOJ1758[Wc2010]重建计划——分数规划+长链剖分+线段树+二分答案+树形DP
    BZOJ4543[POI2014]Hotel加强版——长链剖分+树形DP
    树链剖分讲解及总结(重链剖分+长链剖分)
    Dubbo(3)--dubbo的源码分析
    Dubbo(1)--初识Dubbo
    zookeeper(5)--基于watcher原理实现带注册中心的RPC框架
    模板方法模式
    单例模式
  • 原文地址:https://www.cnblogs.com/airycode/p/7666161.html
Copyright © 2011-2022 走看看