mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:17:26 +08:00
Update
This commit is contained in:
29
problems/0575.分糖果.md
Normal file
29
problems/0575.分糖果.md
Normal file
@ -0,0 +1,29 @@
|
||||
## 题目地址
|
||||
https://leetcode-cn.com/problems/distribute-candies/
|
||||
|
||||
## 思路
|
||||
|
||||
因为种类是可妹妹先来,所以思路先求出一共有多少种糖果,然后如果糖果种类大于candies的一半了,return candies的一半,否则,就是return 糖果的数量就可以了。
|
||||
|
||||
|
||||
## 代码
|
||||
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
int distributeCandies(vector<int>& candies) {
|
||||
std::vector<int> hashTable(200001, -1); // 初始化一个hashtable,因为数字的大小在范围[-100,000, 100,000]内,所以这个hashtable大小要是200001,这样才能取到200000这个下表索引
|
||||
for (int i = 0; i < candies.size(); i++) {
|
||||
hashTable[candies[i] + 100000]++;
|
||||
}
|
||||
int count = 0;
|
||||
for (int i = 0; i < hashTable.size(); i++) {
|
||||
if (hashTable[i] != -1) {
|
||||
count ++;
|
||||
}
|
||||
}
|
||||
int half = candies.size() / 2;
|
||||
return count > half ? half : count;
|
||||
}
|
||||
};
|
||||
```
|
Reference in New Issue
Block a user