LeetCode刷题记录(第十二天)

Distribute Candies

原题目:

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. 


思路:

首先,兄弟姐妹们平分这些糖果,所以,姐妹能拿到不同类别最多种类的糖果就只能是n/2种,n是糖果的总数,也就是数组的长度。

所以我的想法很简单:1、遍历数组,碰到不相同的糖果就放入一个新的数组;

2、最后看新数组的长度与n/2相比较,如果大于等于,则返回n/2,否则返回新数组的长度。

以下是我写的代码:

package com.mianshi.suanfa.DistributeCandies;

/**
 * Created by macbook_xu on 2018/4/1.
 */
public class Solution {
    public static int distributeCandies(int[] candies) {
        int a = 1;

        for (int i = 1 ; i<candies.length ; i++){
            if (candies[i]!=candies[i-1]){
                a++;
            }
        }

        if (a>=candies.length/2) return candies.length/2;
        else return a;
    }
}

但是我的代码是建立在传入的数组为排序后的数组的,当然,如果是无序的,咱们可以自己排一下,而且我没定义新的数组,这么想只是方便理解。

官方的答案给出了四种方法,下面给大家看两种简单明了的方法(有两种方法比较复杂,不太好理解,而且效率并不是很好):

public class Solution {
    public int distributeCandies(int[] candies) {
        Arrays.sort(candies);
        int count = 1;
        for (int i = 1; i < candies.length && count < candies.length / 2; i++)
            if (candies[i] > candies[i - 1])
                count++;
        return count;
    }
}

这种方法和我的想法是差不多的,先进行排序,他是判断当前数比前一个大,和我的判断不相等是一个道理。

public class Solution {
    public int distributeCandies(int[] candies) {
        HashSet < Integer > set = new HashSet < > ();
        for (int candy: candies) {
            set.add(candy);
        }
        return Math.min(set.size(), candies.length / 2);
    }
}

这个方法使用了set,看了这个方法,我知道为什么面试总会问关于集合的问题了,确实在解决问题的使用恰当会非常的方便,利用hashset中元素不可重复,直接就可以求出不同的糖果数目,嘿嘿。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值