Problem
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
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: 2
Explanation: 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.
Note:
The length of the given array is in range [2, 10,000], and will be even.
The number in given array is in range [-100,000, 100,000].
class Solution { public int distributeCandies(int[] candies) { Setset = new HashSet<>(candies.length); for (int candy: candies) set.add(candy); return Math.min(candies.length/2, set.size()); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72317.html
摘要:题目链接题目分析给定一个偶数长度的数组,不同数字代表不同类型的糖果。这一把糖果需要均分给两个人。计算最多能拿到多少种糖果。思路最极端的情况,每一个都是不同的糖果。那么可以获得数组长度除以种糖果。此时,数组内不同元素的个数。 575. Distribute Candies 题目链接 575. Distribute Candies 题目分析 给定一个偶数长度的数组,不同数字代表不同类型的糖...
摘要:题意给出一串二进制数组,求数组中最长的连续的个数思路遍历数组判断,然后将值添加到长度保存数组中,取保存数组最大值。本题要考虑输入的数组为的状况。代码题意给出一个,从里面获取两个数。 485 Max Consecutive Ones题意:给出一串二进制数组,求数组中最长的连续1的个数思路:遍历数组判断,然后将值添加到长度保存数组中,取保存数组最大值。本题要考虑输入的数组为[0],[1]的...
摘要:贪心法复杂度时间空间思路典型的贪心法,如果一个孩子比另一个孩子的分高,我们只多给块糖。我们可以先从左往右遍历,确保每个孩子根他左边的孩子相比,如果分高,则糖要多个,如果分比左边低,就只给一颗。 Candy There are N children standing in a line. Each child is assigned a rating value. You are gi...
摘要:保证高的小朋友拿到的糖果更多,我们建立一个分糖果数组。首先,分析边界条件如果没有小朋友,或者只有一个小朋友,分别对应没有糖果,和有一个糖果。排排坐,吃果果。先往右,再往左。右边高,多一个。总和加上小朋友总数,就是要准备糖果的总数啦。 Problem There are N children standing in a line. Each child is assigned a rat...
摘要:题目要求假设有个孩子站成一排,每个孩子拥有一个评估值。我们可以观察到,每次最远只需要额外分发到距离当前最近的评分最高的那个孩子。因为他的糖果数量的增加并不会影响到之前孩子。当有多个最近评分最高的孩子时,则选择最后一个。 题目要求 There are N children standing in a line. Each child is assigned a rating value....
阅读 3715·2021-10-14 09:43
阅读 3311·2021-08-25 09:38
阅读 608·2019-08-30 15:55
阅读 1342·2019-08-30 13:05
阅读 2237·2019-08-29 16:05
阅读 500·2019-08-29 12:58
阅读 2790·2019-08-29 12:34
阅读 3241·2019-08-26 12:15