LeetCode - 575. Distribute Candies
题目链接地址:
https://leetcode.com/problems/distribute-candies/description/
题目大意:
给定一个偶数长度的整数数组,数组中的不同数字代表不同种类的糖果。每一个数字意味着相应的一个糖果。你需要把这些糖果均匀地分配给弟弟和妹妹。返回姐姐能得到的糖果的最大数量。
样例1
输入:糖果= [ 1,1,2,2,3,3 ]
输出:3
解释:
有三种不同的糖果(1, 2和3),每种糖果两种。
优化配置:姐姐有糖果[1,2,3],弟弟有糖果[1,2,3],也。
姐姐有三种不同的糖果。
样例2
输入:糖果= [ 1,1,2,3 ]
输出:2
说明:例如,妹妹有糖果(2,3),而兄弟有糖果(1,1)。
姐姐有两种不同的糖果,弟弟只有一种糖果。
算法思路
第一种:先对数组排序,那么同种糖果归类到了一起。只需遍历数组,每种糖果取一种,直到数量达到一半。
第二种:直接将每种糖果存入set,则可获得所有糖果的种类,若种类大于一半,则返回数组长度的一半(因为妹妹最多获得一半数量糖果)
java代码实现
class Solution {
public int distributeCandies(int[] candies) {
Set<Integer> kinds = new HashSet<>();
for (int candy : candies) kinds.add(candy);
return kinds.size() >= candies.length / 2 ? candies.length / 2 : kinds.size();
}
}
public class MainClass {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int[] candies = stringToIntegerArray(line);
int ret = new Solution().distributeCandies(candies);
String out = String.valueOf(ret);
System.out.print(out);
}
}
}
浙公网安备 33010602011771号