class Solution {
public:
int distributeCandies(vector<int>& candyType) {
unordered_map<int,int>m;
int l=candyType.size();
int t=0;
for(int i=0;i<l;i++)
{
if(m.count(candyType[i])==0)
{
m.insert(make_pair(candyType[i],1));
++t;
}
}
if(t<l/2)
{
return t;
}
else
{
return l/2;
}
}
};
使用了哈希表来求解,结果并不是很好看。
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
int t=1;
int l=candyType.size();
sort(candyType.begin(),candyType.end());
for(int i=1;i<l;i++)
{
if(candyType[i-1]!=candyType[i])
{
++t;
}
}
if(t<l/2)
{
return t;
}
else
{
return l/2;
}
}
};
重新写了一个题解,时间和空间都有很大提升。
主要是题简单。
加油!