当前位置:网站首页>力扣每日一题-第29天-575.分糖果
力扣每日一题-第29天-575.分糖果
2022-06-28 02:43:00 【重邮研究森】
2022.6.27今天你刷题了吗?
题目:
Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。
医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。
给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的 最多 种类数。
分析:
给你一个偶数数组,你需要找到数组大小的一半的值x,和不同元素的类型y进行比较,如果x大于等于y,则返回y,否则返回x。
思路:我们利用map容器把元素插入,然后根据map的大小和原数组一半大小进行比较可以得到结果
解析:
1.哈希表
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
unordered_map<int, int>map;
int n = candyType.size() / 2;
int res = 0;
for (auto num : candyType)
{
map[num]++;
}
int m = map.size();
if (n <= m)
{
res = n;
}
else
{
res = m;
}
return res;
}
};
2.set容器
因为不考虑重复元素,可以直接存入set容器中,并且在插入set时进行了优化。因为map需要同时插入键值和键值对所以不能这样执行。
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
unordered_set<int>set(candyType.begin(), candyType.end());
int s = set.size();
int res = min(s, (int)candyType.size() / 2);
}
};
边栏推荐
- Notepad++--常用的插件
- nn. Parameter and torch nn. Init series of functions to initialize model parameters
- More, faster, better and cheaper. Here comes the fastdeploy beta of the low threshold AI deployment tool!
- WebSocket(简单体验版)
- kubernetes资源对象介绍及常用命令
- Sublime Text 3 基本配置教程
- 文件的相对路径写法
- [games] Parkour
- 导入Excel文件,解决跳过空白单元格不读取,并且下标前移的问题,以及RETURN_BLANK_AS_NULL报红
- Importer un fichier Excel, résoudre le problème de sauter les cellules vides et de ne pas lire, et avancer l'indice, et retourner Blank As NULL Red
猜你喜欢
__getitem__和__setitem__
Redis搭建集群【简单】
2022 electrician (elementary) recurrent training question bank and online simulation examination
Importer un fichier Excel, résoudre le problème de sauter les cellules vides et de ne pas lire, et avancer l'indice, et retourner Blank As NULL Red
可扩展系统的“9不”原则和“5个”衡量维度
【小程序】使用font-awesome字体图标的解决文案(图文)
GAMES104 作业2-ColorGrading
数据库系列之MySQL配置F5负载均衡
Go speed
2022电工(初级)复训题库及在线模拟考试
随机推荐
如何给Eclips自动添加作者,时间等…
Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red
Establishment of SSH Framework (Part I)
How to write concise code? (upper)
R1 Quick Open Pressure Vessel Operation Special Operation Certificate Examination Library and Answers in 2022
空闲中断无法清除
数据库系列之MySQL和TiDB中慢日志分析
物体上下漂浮工具
service实现类里面为何一直报红
用于 C# 的 SQL 基本语法总结
Object类,以及__new__,__init__,__setattr__,__dict__
如何获取GC(垃圾回收器)的STW(暂停)时间?
Apache - Introduction à Apache
文件的相对路径写法
PPT制作小技巧
17 `bs object Node name h3 Parent ` parents get parent node ancestor node
WPF 下的自定义控件以及 Grid 中控件的自适应
MySQL 数据库的自动备份操作
失联修复:让“躲猫猫”无处可藏
Custom controls under WPF and adaption of controls in Grid