将分糖果问题转化为确定种类问题,当超过一半就输出一半,没超过就输出种类。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
int i = 0; int j = 0; int dif = -1000000;
while (i <candyType.size())
{
if (candyType[i] != dif)
{
j++;
dif = candyType[i];
}
i++;
}
if (j >= (candyType.size() / 2))
{
return candyType.size() / 2;
}
else
{
return j;
}
}
};
int main()
{
vector<int> a = { 1, 2, 3, 4, 4, 5,5,5,5,5,5 };
Solution b;
cout <<b.distributeCandies(a);
system("pause");
return 0;
}