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中元素不可重复,直接就可以求出不同的糖果数目,嘿嘿。