[LeetCode]575. Distribute Candies(妹妹最多能得到多少种糖果)

来源:互联网 发布:淘宝买彩票安全吗 编辑:程序博客网 时间:2024/05/22 20:28

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.

Example 1:

Input: candies = [1,1,2,2,3,3]Output: 3Explanation: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: 2Explanation: 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:

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

题目大意:
给一个长度为偶数的整数数组,数组中不同数字都代表不同糖果,将糖果平均分给弟弟和妹妹,妹妹最多能得到几种糖果。

思路:

  • 记录糖果种类,若糖果种类大于数组的一半,妹妹最多得到candies.size()/2种糖果,否则每种糖果都可以得到

代码1:

  • 用hash表。
  • 定义unordered_map《int, int> HASH,定义一个整数res存储妹妹能得到糖果的种类
  • 遍历数组,将每个数字存到对应位置中,如果存入后这个数字对应位置的数(该种糖果数量)等于1且res小于数组长度的一半,res++,最后返回res
#include <vector>#include <unordered_map>int distributeCandies(vector<int>& candies) {        if(candies.size()%2 != 0)            return 0;        unordered_map<int, int> HASH;        int res = 0;        for(int c: candies){           HASH[c]++;           if(HASH[c]==1 && res<candies.size()/2)                res++;        }        return res;    }

代码2:

  • 排序后遍历
  • 若是记录糖果种类,不用额外的内存占用,只需要定义一个整数res
#include <iostream>#include <vector>#include <assert.h>#include <algorithm>using namespace std;class Solution {public:    int distributeCandies1(vector<int>& candies) {        assert(candies.size()%2 == 0);//assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行        sort(begin(candies), end(candies));//将数组排序        int ans = 0;//记录糖果种类        for (int i=0; i<candies.size(); ++i) {            if(i==0 || candies[i]!=candies[i-1])                ++ans;        }        return min(ans, (int)candies.size()/2);    }};int main(){    Solution a;    int candies[] = {1, 1, 1, 2, 2, 2, 3, 4};    int candiesLength = sizeof(candies)/sizeof(candies[0]);    vector<int> Candies(candies, candies+candiesLength);    cout << "the maximum number of kinds of candies the sister could gain is ";    cout << a.distributeCandies(Candies) << endl;    return 0;}
0 0
原创粉丝点击