每日一题:7. 分糖果(C++)

编程入门 行业动态 更新时间:2024-10-18 03:27:34

每日一题:7. 分<a href=https://www.elefans.com/category/jswz/34/1761997.html style=糖果(C++)"/>

每日一题:7. 分糖果(C++)

每日一题:7. 分糖果(C++)

题目
Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。

医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。

给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的最多种类数。

解题思路:

  1. 从糖果的所有不同种类和所有糖果数作为切入点,遍历所有糖果得到不同种类个数
  2. 当糖果种类大于总数一半时便得到了结果为总数的一半,到此便可以结束代码的运算(剪枝)
  3. 否则遍历完所有糖果,说明种类数量少于糖果一半,返回得到的种类个数

代码(1.最简代码,集合——Set)

class Solution {
public:int distributeCandies(vector<int>& candyType) {return min(unordered_set<int>(candyType.begin(), candyType.end()).size(), candyType.size() / 2);}
};

代码(2.集合——Set,优化,枝剪)

class Solution {
public:int distributeCandies(vector<int>& candyType) {set<int> result;for(int i = 0, count = 0; count < candyType.size() / 2 && i < candyType.size(); i ++){if(result.insert(candyType[i]).second) count++;}return result.size();}
};

代码(3.哈希——map,本题最优算法)

class Solution {
public:int distributeCandies(vector<int>& candyType) {vector<bool> temp_sign(200001, false);int count = 0;for(int i : candyType){if(!temp_sign[i + 100000]){temp_sign[i + 100000] = true;count ++;}if(count >= candyType.size() / 2) {break;}}return count;}
};

作者:yi-si-cb(倚肆)
链接:/

更多推荐

每日一题:7. 分糖果(C++)

本文发布于:2024-02-06 17:23:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1750255.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:糖果

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!