糖果(C++)"/>
每日一题:7. 分糖果(C++)
每日一题:7. 分糖果(C++)
题目:
Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。
医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。
给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的最多种类数。
解题思路:
- 从糖果的所有不同种类和所有糖果数作为切入点,遍历所有糖果得到不同种类个数
- 当糖果种类大于总数一半时便得到了结果为总数的一半,到此便可以结束代码的运算(剪枝)
- 否则遍历完所有糖果,说明种类数量少于糖果一半,返回得到的种类个数
代码(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++)
发布评论