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<Integer> 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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,614评论 0 23
  • 这两天脑海里就只有钥匙,锁,了。可见文章我以深入脑海。 我今天要做一次深入的自我检讨:打开我的锁。 ...
    开心乐佳阅读 918评论 0 0
  • 很多人说,家怎么可能成为美容院,那简直太不可思议了? 这个词语是从我脑子里面蹦出来的,因为每个人都喜欢美好的事物,...
    知恩艺生阅读 234评论 0 1
  • 感恩小区清洁阿姨,让我有个好的生活环境。 感恩保安帅哥,每天给我开门关门。 感恩儿子在我不舒服的时候暖暖的问候。 ...
    双球儿阅读 121评论 0 0
  • 长发飘飘的美好
    叶小言阅读 263评论 1 0

友情链接更多精彩内容