Leetcode——575. Distribute Candies

题目原址

https://leetcode.com/problems/distribute-candies/description/

题目描述

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.

Example1:

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.

Example2:

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].

解题思路

题目的意思是:给一个整型数组,数组的长度为偶数个,数组中的值不同代表不同的类型的糖,现在想要将所有的糖平分给哥哥姐姐,即哥哥姐姐的糖数应该相同。在这个条件下,想要让姐姐得到更多种类的糖,问姐姐能得到最多多少类糖。

解题的方法也比较简单,首先定义一个map集合,因为最后要计算有多少个不同类型的糖,所以使用map,因为map有keySet方法,可以将key全部便利出来。

  • 使用for循环将糖放入map集合中
  • 使用增强for循环来计算有多少个不同的糖
  • 如果不同类型的糖的个数大于num,则说明小姐姐分到的糖可以都不同;否则,有多少个不同类型的糖就只能分到多少个不同类型的糖了。(num为将总糖数一分为二,姐姐能分得的糖的个数)

AC代码

class Solution {
    public int distributeCandies(int[] candies) {
        int count = 0;
        int num = candies.length / 2;
        int sum = 0;
        Set<Integer> set = new HashSet<Integer>();
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int a: candies) {
            map.put(a, count);
        }
        //有多少种不同的糖
        for(Integer i : map.keySet()){
            sum++;
        }
        if(sum >= num)
            return num;
        else
            return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值