当前位置:网站首页>力扣每日一题-第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);
}
};边栏推荐
猜你喜欢

2022 safety officer-c certificate examination question bank simulated examination platform operation

Etcd database source code analysis -- network layer server rafthandler between clusters

Question bank and answers of special operation certificate for R1 quick opening pressure vessel operation in 2022

matlab习题 —— 符号运算相关练习

mysql获取当前时间是一年的第多少天

荣耀v8 真机调试时不显示 Logcat 日志的解决办法

根据Explain查看sql执行计划,对SQL进行优化

In the digital era, enterprises must do well in user information security

失联修复:让“躲猫猫”无处可藏

2022电工(初级)复训题库及在线模拟考试
随机推荐
被校园暴力,性格内向的马斯克凄惨而励志的童年
The same is MB. Why is the gap so large?
数据库系列之MySQL和TiDB中慢日志分析
matlab习题 —— 数据的基本处理
Dataloader参数collate_fn的使用
一位博士在华为的22年(干货满满)
数字化时代,企业须做好用户信息安全
mysql获取当前时间是一年的第多少天
劲爆!YOLOv6又快又准的目标检测框架开源啦(附源代码下载)
SSH框架的搭建(下)
可扩展系统的“9不”原则和“5个”衡量维度
剑指 Offer 49. 丑数(三指针法)
MySQL 数据库的自动备份操作
xml&nbsp;文件的读写
Ten reasons for system performance failure
17 `bs object Node name h3 Parent ` parents get parent node ancestor node
启牛商学院赠送证券账户是真的吗?开户到底安不安全呢
__getitem__和__setitem__
nn. Parameter and torch nn. Init series of functions to initialize model parameters
栈的基本操作(C语言实现)