当前位置:网站首页>力扣每日一题-第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);
}
};边栏推荐
- Build your own website (17)
- WPF 下的自定义控件以及 Grid 中控件的自适应
- 被校园暴力,性格内向的马斯克凄惨而励志的童年
- nn. Parameter and torch nn. Init series of functions to initialize model parameters
- Notepad++--列编辑模式--用法/实例
- ETCD数据库源码分析——集群间网络层服务端RaftHandler
- 一位博士在华为的22年(干货满满)
- 云应用、服务的“5层”架构
- Tencent games released more than 40 products and projects, including 12 new games
- Go 数据类型篇(四)之浮点型与复数类型
猜你喜欢

【小程序】使用font-awesome字体图标的解决文案(图文)

剑指 Offer 47. 礼物的最大价值(DP)

暴雨去哪儿?天气预报不准谁的锅?

【iptables&icmp】iptables默认策略中关于icmp协议的说明

2022安全员-C证考试题库模拟考试平台操作

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

音视频技术开发周刊 | 251

Why is the service implementation class always red

Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red

基于 LNMP 搭建个人网站的填坑之旅
随机推荐
基于 LNMP 搭建个人网站的填坑之旅
Go 数据类型篇(四)之浮点型与复数类型
PPT制作小技巧
2022 operation of simulated examination platform of special operation certificate examination question bank for safety management personnel of hazardous chemical business units
TypeScript 联合类型
Necessary software tools in embedded software development
Arm development studio build compilation error
为什么OpenCV计算的帧率是错误的?
Tencent games released more than 40 products and projects, including 12 new games
A pit filling trip based on LNMP to build a personal website
What is the difference between slice and array in go question bank 12?
Win10 如何删除系统盘大文件hiberfil.sys
composition api在项目中的使用总结
劲爆!YOLOv6又快又准的目标检测框架开源啦(附源代码下载)
JS clear the object and its value:
Is it safe to buy stocks and open an account through the account opening link of the broker manager? Want to open an account for stock trading
【iptables&icmp】iptables默认策略中关于icmp协议的说明
Redis cluster setup [simple]
Object class, and__ new__,__ init__,__ setattr__,__ dict__
SSH框架的搭建(下)