题目大意:有一些不同种类的糖果,男生女生各得一半数量的糖果,问女生最多可能得到多少种不同种类的糖果。
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:
1 2 3 4 5 6 |
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:
1 2 3 4 |
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. |
Note:
- The length of the given array is in range [2, 10,000], and will be even.
- The number in given array is in range [-100,000, 100,000].
Solution 1: Greedy
Give all unique candies to sisters until they have n/2 candies.
Time complexity: O(n)
Space complexity: O(n)
C++ Hashset
1 2 3 4 5 6 7 8 9 |
// Author: Huahua // Running time: 258 ms class Solution { public: int distributeCandies(vector<int>& candies) { unordered_set<int> kinds(candies.begin(), candies.end()); return min(kinds.size(), candies.size() / 2); } }; |
C++ Bitset
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua // Running time: 195 ms (beats 97.61%) class Solution { public: int distributeCandies(vector<int>& candies) { constexpr int kMaxKinds = 200001; constexpr int kOffset = 100000; bitset<kMaxKinds> s; for (int candy : candies) if (!s.test(candy + kOffset)) s.set(candy + kOffset); return std::min(s.count(), candies.size() / 2); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment