LeetCode解题思路:575. Distribute Candies

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode解题思路:575. Distribute Candies相关的知识,希望对你有一定的参考价值。

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.

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. 

Note:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].

题意:给一个偶数长度的数组,不同的数字表示不同的蜡烛,需要将蜡烛平均分给哥哥和妹妹,返回妹妹能拿到的最多种蜡烛数量。

基本思路:

1.先让妹妹从蜡烛数组里面选,如果妹妹的蜡烛达到数组的一半,那就停止,返回妹妹手里的数量;如果没达到一半,就让妹妹接着选重复的蜡烛,最后返回妹妹手中蜡烛的种类。

代码如下:

 1 int distributeCandies(int* candies, int candiesSize) {
 2     int len = candiesSize/2;
 3     char arr[200002] = {0};
 4     int i = 0,cnt = 0;
 5     for(;i<candiesSize; ++i )
 6     {
 7         if(arr[candies[i]+100001])
 8             continue;
 9         else{
10             arr[candies[i]+100001] = 1;
11             ++cnt;
12         }
13         if(cnt >= len)
14             return cnt;
15     }
16     cnt = 0;
17     for(int i=0; i<candiesSize;++i)
18         if(arr[candies[i]+100001] == 1)
19             cnt++
20     return cnt;
21 }

2.以上代码有些地方可以优化,就是妹妹不管最后拿到的蜡烛是不是完全不重复的,她都只能拿到n/2,而且如果种类小于n/2,那再拿多少种类也不会增多了。综合这两点考虑的话,所以尽管让妹妹拿然后统计她拿的数量 就好了,不到n/2就拿完就返回数量,否则返回n/2,代码如下:

 1 int distributeCandies(int* candies, int candiesSize) {
 2     int len = candiesSize/2;
 3     char arr[200002] = {0};
 4     int i = 0,cnt = 0;
 5     for(;i<candiesSize && cnt <candiesSize/2; ++i )
 6     {
 7         if(arr[candies[i]+100001])
 8             continue;
 9         else{
10             arr[candies[i]+100001] = 1;
11             ++cnt;
12         }
13         if(cnt >= len)
14             break;
15     }
16     return cnt;
17 }

当然C++可以利用stl容器中的set或者unordered_set进行筛选,并用min方法返回种类和n/2中较小的那个。

 1 class Solution {
 2 public:
 3     int distributeCandies(vector<int>& candies) {
 4         unordered_set<int> kinds;
 5         for (int kind : candies) {
 6             kinds.insert(kind);
 7         }
 8         return min(kinds.size(), candies.size() / 2);
 9     }
10 };

 

以上是关于LeetCode解题思路:575. Distribute Candies的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 575 分糖果[set] HERODING的LeetCode之路

解题报告Leecode. 575. 分糖果——Leecode每日一题系列

leetcode打卡——去重之575. 分糖果

Leetcode题解....ing python

LeetCode解题思路

leetcode剑指offer合集+题解