575. Distribute Candies

分糖。这是weekly contest 31的第一题。在西安星巴克做的。

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.

hashset

这题我上来就用set做了。

    public int distributeCandies(int[] candies) {
        HashSet set = new HashSet<>();
        for (int i = 0; i < candies.length; i++) {
            if (set.size() < candies.length / 2) {
                set.add(candies[i]);
            }
        }
        return set.size();
    }

时间和空间都是O(n)。

leetcode新题里面大部分都有editorial solution,很6。
我看了下这题,也给出了很多种方式:
Approach #1 Brute Force [Time Limit Exceeded]
Approach #2 Better Brute Force [Time Limit Exceeded]
Approach #3 Using sorting[Accepted]
Approach #4 Using set [Accepted]

其中第一种解法虽然看起来很蠢但是对于我很有参考价值。。
他把所有的排列全部罗列一遍,然后观察这些排列中前一半的不相同的数字的size。。也用了set,很蠢,因为直接travese一遍就可以了。甚至说可以在set的size等于一半的时候就不再执行了。但是他permute的写法很6,递归然后swap。用笔在纸上画画模拟比较容易。第一位和第二位换,第二位和第三位换。。依此类推,换到头了再回来继续换。

第二种解法太长没看。

第三种解法是用sort,然后判断前一半的不同的数字的长度。

So much for this.

你可能感兴趣的:(575. Distribute Candies)