leetcode 575 分糖果 python與c++
阿新 • • 發佈:2021-02-01
技術標籤:leetcodpythonc++leetcode演算法
文章目錄
一、思路
種類問題一般都可以考慮雜湊(或set)。
首先我們統計有多少類糖果(用set應該也可以),然後妹妹先挑,要求種類最多,如果種類數
c
o
u
n
t
count
count小於等於糖果個數的一半,那麼妹妹無論怎麼挑,最多也就是
c
o
u
n
t
count
count種。如果種類數
c
o
u
n
t
count
count大於糖果個數的一半(比如[1,1,2,3,4,4],4種),妹妹最多隻能拿糖果個數的一半的糖果(這個例子中是3個),所以這道題就很簡單了,只需要比較一下種類數和糖果個數的關係即可。
二、程式碼
1.python
程式碼如下:
class Solution:
def distributeCandies(self, candyType) :
dic = {}
n = len(candyType)
for i in candyType:
dic[i] = dic.get(i,0) + 1
count = len(dic)
return len(candyType)//2 if count > len(candyType)//2 else count
2.C++
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
map<int,int> m;
int count = 0, half = 0;
for(int i =0; i<candyType.size();i++){
m[candyType[i]]++;
}
count = m.size();
half = candyType.size()/2;
return count > half ? half : count;
}
} ;