分糖
来源:互联网 发布:道路噪声预测软件 编辑:程序博客网 时间:2024/04/29 06:49
1.问题描述
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: 3Explanation: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: 2Explanation: 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].
2.解释:
这道题给我们一堆糖,每种糖的个数不定,分给两个人,让我们求其中一个人能拿到的最大的糖的种类数。那么我们想,如果总共有n个糖,平均分给两个人,每人得到n/2块糖,那么能拿到的最大的糖的种类数也就是n/2种,不可能再多,只可能再少。那么我们要做的就是统计出总共的糖的种类数,如果糖的种类数小于n/2,说明拿不到n/2种糖,最多能拿到的种类数数就是当前糖的总种类数,明白了这点就很容易了,我们利用集合set的自动去重复特性来求出糖的种类数,然后跟n/2比较,取二者之中的较小值返回即可,
3.代码
public int distributeCandies(int[] candies) { HashSet set = new HashSet(); for (int candy : candies) { set.add(candy); } if (set.size() <= candies.length/2){ return set.size(); }else { return candies.length /2; } }
阅读全文
0 0
- 分糖
- 分糖
- 【孩子分糖】
- 孩子分糖问题----
- 1/7 分糖
- 分
- 分
- 分
- 分
- ZJUT1551 分糖 01背包
- 【孩子分糖】-leecode-OJ
- LeetCode练习<七> 分糖
- N个孩子站一行分糖
- Java中部分常见语法糖
- 专家分5分
- 分库 分表
- 1083 -- 分!分!分! 学生的命根
- 1259: 分!分!分! 学生的命根
- Dassault.Systemes.Simulia.XFlow.2017.Win64 1DVD
- 抽象类-学生-研究生-收入-教师
- 前言
- Mysql中两种引擎的区别
- 计算机网络
- 分糖
- Win7下运行VC程序UAC权限问题
- Oracle 增加、修改、删除字段与添加注释
- 如何将Eclipse中Web项目打成war包
- Android 仿京东分类
- 初始化顺序及RAM的一些概念
- OkHTTP二次封装加拦截器
- NLP基础--词性含义
- Android-PickerView系列之介绍与使用篇(一)