首页 > 编程语言 >LeetCode-Java-575. Distribute Candies

LeetCode-Java-575. Distribute Candies

时间:2022-12-14 15:02:07浏览次数:61  
标签:sister Java Candies Distribute different number candies int kinds


题目

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.
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].

代码

只需要比较数组的一半大还是数组内不同的数字数目多

class Solution {
public int distributeCandies(int[] candies) {
int len = candies.length;
HashSet<Integer> set = new HashSet<Integer>();
for(int i=0;i<len;i++){
set.add(candies[i]);
}
int c = len/2;
return set.size()>c?c:set.size();
}
}


标签:sister,Java,Candies,Distribute,different,number,candies,int,kinds
From: https://blog.51cto.com/u_12938555/5936996

相关文章

  • 剑指Offer-Java-重建二叉树
    题目输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍......
  • 剑指Offer-Java-序列化二叉树
    题目请实现两个函数,分别用来序列化和反序列化二叉树代码此题的核心点是如何表示二叉树,并且解释。/*publicclassTreeNode{intval=0;TreeNodeleft=null;......
  • Java做UI自动化和app自动化中动态代理@FindBy的工作原理【杭州多测师_王sir】【杭州多
    Java做UI自动化和app自动化中动态代理@FindBy的工作原理一、背景简介由于Selenium框架采用PageObject设计模式让测试代码与被测页面对象代码分离,因而提供了不少很方便的注......
  • 【都 Java19 了,还不了解 Java 8 ? 】一文带你深入了解 Java 8 新特性
    Java8(又称为jdk1.8)是Java语言开发的一个主要版本。Oracle公司于2014年3月18日发布Java8,它支持函数式编程,新的JavaScript引擎,新的日期API,新的Stream......
  • JAVA-枚举使用
    枚举在本教程中,我们将了解什么是Java枚举、它们解决的问题以及它们的一些设计模式如何在实践中使用。1.概述Java5首先引入了enum关键字。它表示一种特殊类型的类,它总......
  • 巨蟒python全栈开发数据库前端5:JavaScript1
     1.js介绍&变量&基础数据类型2.类型查询&运算符&if判断&for循环3.while循环&三元运算符4.函数5.今日总结 1.js介绍&变量&基础数据类型js介绍(1)什么是JavaScript&一些历史......
  • Java8新特性
    一、Java8新特性1.Lambda表达式Lambda是匿名函数,使用它可以写出简洁,灵活的代码。  a.表达式无参数,无返回值,只有一个Lambda体Runnable r1=()->log.info......
  • Java面向对象2
    封装性    封装就是保护内容,保证某些属性或方法可以不被外部看见,而在内部自己去处理。 classPerson{Stringname;intage;publicvoidtell(){System.out......
  • Java面向对象1
     程序的发展阶段程序的发展经历了两个主要阶段:面向过程、面向对象。对于面向对象与面向过程可以用一个例子解释,如一个木匠要做一个盒子,那么做这个盒子的出发点会有两种......
  • 50个Java面试必问的面试题,我都给你整好了
    ​我们整理了一份主要的Angular面试问题清单,分为三部分:角度面试问题–初学者水平角度面试问题–中级角度面试问题–高级初学者水平–面试问题1.区分Angular和Angula......