lintcode/leetcode由易至难第7题:Distribute Candies

来源:互联网 发布:c语言向上取整函数 编辑:程序博客网 时间:2024/06/05 14:58

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. 
Code1:

public class Solution {    public int distributeCandies(int[] candies) {        int a = candies.length;        Arrays.sort(candies);        int count = 1;        for(int i = 0;i < (a-1); i++){            if(candies[i] != candies[i+1])count++;        }        return Math.min(count , a/2);    }}

Code2:

public class Solution {    public int distributeCandies(int[] candies) {        Set<Integer> cat = new HashSet<>();//尝试使用HashSet        for(int candy : candies){            cat.add(candy);        }        return cat.size() >= candies.length/2 ? candies.length/2 : cat.size();  //新接触的三目运算符    }}

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 天天中彩票怎么登陆不了怎么办 正宇新商城不能提现怎么办 融e购买完不发货怎么办 婴儿肚子胀气肚脐凸出来怎么办 微信商城买东西被骗了怎么办 拼多多商家不发货怎么办 鞋上的饰品掉了怎么办 饰品上的钻掉了怎么办 dota2饰品被好友礼物怎么办 dota2接收的礼物打不开怎么办 英雄联盟线上被压制怎么办 云联商城的钱怎么办 高顿财经不退款怎么办 拼多多连不上网怎么办 拼多多评分太低怎么办 拼多多限制提现怎么办 手机收不到验证码怎么办 淘宝未发货怎么取消退款怎么办 羊皮的鞋子刮坏怎么办 退货寄错了东西怎么办 毒app上买鞋尺码不合适怎么办 拼多多一直不发货怎么办 天猫国际买东西被税要退货怎么办 国外快递被税了怎么办 手机上传图片时过大怎么办 原网页被重新排版怎么办 文件目录损坏且无法读取怎么办 360木马查杀蓝屏怎么办 电脑上传的文件大小超过限制怎么办 文件最大不超过200m怎么办 抖音上传文件太大怎么办 下载ppt变成php文件怎么办 数据库bak文件损坏了怎么办? wps文档大小超出上传限制怎么办 手机百度用微盘下载不了文件怎么办 无法读取源文件或磁盘怎么办 文件中转站未安装上传控件怎么办 手机外国网址网速太差怎么办 istpng里显示不出图片怎么办 电脑上保持登录状态后怎么办 电脑打游戏闪退怎么办