当前位置:网站首页>day575: 分糖果
day575: 分糖果
2022-06-22 09:18:00 【浅浅望】
问题:分糖果
给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
示例 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],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。
来源:力扣(LeetCode)
思路一:集合(set)
- 如果糖果种类大于n/2,n为总糖果数,则妹妹最多可获得n/2种糖果。
- 如果糖果种类为m,m<n/2,则妹妹最多可得m种糖果。
- 由此可得,妹妹最多获得糖果种类数为min(m,n/2)。
class Solution {
public int distributeCandies(int[] candyType) {
Set<Integer> candyTypeSet = new HashSet<Integer>();
for(int candy : candyType){
candyTypeSet.add(candy);
}
return Math.min(candyTypeSet.size(),candyType.length/2);
}
}
思路二:排序
- 对数组进行排序;
- 找出数组种共有多少种糖果;
- 返回数组长度的一半与糖果种类中的最小值。
class Solution {
public int distributeCandies(int[] candyType) {
Arrays.sort(candyType);
int count = 1;
for(int i=1; i<candyType.length; i++){
if(candyType[i]>candyType[i-1])
count += 1;
}
return Math.min(count,candyType.length/2);
}
}
边栏推荐
猜你喜欢

MySQL中常用的SQL语句

Zabbix5系列-使用温湿度传感器监控机房温湿度 (二十)

Shengdun technology joined dragon lizard community to build a new open source ecosystem

在ensp上做多出口服务器映射

Project optimization + online (Master?)

Value (address) transmission, see the name clearly, don't fall into the ditch

锁-ReentrantLock

Apprentissage automatique | nltk Erreur de téléchargement des données | solution d'erreur de téléchargement du corpus stopwords pour nltk
![[uni app] actual combat summary (including multi terminal packaging)](/img/35/6b0672311b033bc89f1518dd794777.png)
[uni app] actual combat summary (including multi terminal packaging)

Langchao state-owned assets cloud: state-owned assets as a guide to help state-owned enterprises use data to enrich their wisdom in the cloud
随机推荐
MySQL中常用的SQL语句
Brush questions in C language | output love (14) with putchar
接口抽象类的比较
pytorch的模块使用:线性模型(未完成)
DOM programming
Mapping multiple exit servers on ENSP
[node] scaffolding server to complete token verification
[hdu] P1466 计算直线的交点数
Debian10 创建用户、用户组、切换用户
Find the size of cosine
simple_strtoull字符转换相关函数
Map三种遍历方式,秒懂,你懂
在ensp上做防火墙的双机热备
两个线程各执行100次i++,得到的可能值
Network security Kali penetration learning how to conduct Nessus vulnerability detection
Overview of microservice architecture
. A use of file link library
Double machine hot standby of firewall on ENSP
Unicode characters / static non static access
通过docker安装mysql(5.7+8.0)并配置主从复制(GTID+增强半同步)