LeetCode之Distribute Candies
来源:互联网 发布:java项目有红色感叹号 编辑:程序博客网 时间:2024/05/22 12:40
题目概述:
给一个偶数个数的整数数组,数组里相同的数代表同一种糖果,不同的数代表不同种类的糖果,把这些糖果平均分给弟弟和姐姐,返回姐姐可能得到的最多的糖果种类的个数。
思路:
如果糖果的种类数小于数组的一半,返回种类数,否则,返回数组的一半值。
示例:
Example 1:Input: candies = [1,1,2,2,3,3]Output: 3Explanation:There are three different kinds of candies (1, 2 and 3), and two candies for each kind.Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies. Example 2:Input: candies = [1,1,2,3]Output: 2Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.
代码:
class Solution {public: int distributeCandies(vector<int>& candies) { //candies呈升序排列 sort(candies.begin(),candies.end()); //candies数组的长度 int length=candies.size(); //candies的种类数 int num=1; for(int i=1;i<length;i++) { if(candies[i]!=candies[i-1]) { num++; } } if(num>=length/2) return length/2; else return num; }};
另一种解法:
class Solution {public: int distributeCandies(vector<int>& candies) { unordered_set<int> kinds; for (int kind : candies) { kinds.insert(kind); } return min(kinds.size(), candies.size() / 2); }};set集合是无序集合容器。
0 0
- LeetCode之Distribute Candies
- LeetCode | 575. Distribute Candies
- leetcode 575. Distribute Candies
- [LeetCode]575. Distribute Candies
- LeetCode Distribute Candies
- [leetcode]: 575. Distribute Candies
- [leetcode]575. Distribute Candies
- LeetCode 575. Distribute Candies
- leetcode.575. Distribute Candies
- LeetCode 575. Distribute Candies
- 【LeetCode】575 Distribute Candies
- [LeetCode]575.Distribute Candies
- leetcode 575. Distribute Candies
- LeetCode: 575. Distribute Candies
- LeetCode#575. Distribute Candies
- LeetCode 575. Distribute Candies
- 【LeetCode】575. Distribute Candies
- [LeetCode]575. Distribute Candies
- 【消息队列MQ】从MQ种类说起
- 1080. Graduate Admission 解析
- 关于spark streaming新版本ssc创建不了问题
- cas 4.2.5 返回更多的用户信息
- 多表透视图的制作 第一讲:数据规范化
- LeetCode之Distribute Candies
- PRVG-10122 : ASMLib configuration value
- redis
- 1081. Rational Sum 解析
- 爪哇(Java)的诞生、组成
- 机器学习 VS. 深度学习
- 数据挖掘之决策树介绍
- React Native原生模块向JS传递数据的几种方式(Android)
- Java中初始化和清理