Distribute Candies

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

题意: 给定一组长度为偶数的整数,其中每个数字代表一个糖果的种类标号。将糖果均分给哥哥和妹妹,返回妹妹可以得到的最大糖果种类数。

约定:(1)数组长度范围[2, 10,000],并且为偶数;(2)给定数字范围[-100,000, 100,000]。

例子: 

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. 


标签: candies、sister、brother、kinds、糖果、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • SLPH
    2017-08-13 12:41:16 1楼#1层
    Python:
    class Solution(object):
        def distributeCandies(self, candies):
            """
            :type candies: List[int]
            :rtype: int
            """
            return min(len(candies) / 2, len(set(candies)))
  • SLPH
    2017-08-13 12:41:41 2楼#1层
    C++解法一:
    class Solution {
    public:
        int distributeCandies(vector<int>& candies) {
            unordered_set<int> s;
            for (int candy : candies) s.insert(candy);
            return min(s.size(), candies.size() / 2);
        }
    };
  • SLPH
    2017-08-13 12:41:56 3楼#1层
    C++解法二:
    class Solution {
    public:
        int distributeCandies(vector<int>& candies) {
            return min(unordered_set<int>(candies.begin(), candies.end()).size(), candies.size() / 2);
        }
    };
  • SLPH
    2017-08-13 12:42:22 4楼#1层
    Java:
    public 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();
        }
    }
  • 回复
隐藏