代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers
are placed in an array.
Return the minimum number of rabbits that could be in the forest.
Examples: Input: answers = [1, 1, 2] Output: 5 Explanation: The two rabbits that answered "1" could both be the same color, say red. The rabbit than answered "2" can't be red or the answers would be inconsistent. Say the rabbit that answered "2" was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. Input: answers = [10, 10, 10] Output: 11 Input: answers = [] Output: 0
Note:
answers
will have length at most 1000
.answers[i]
will be an integer in the range [0, 999]
.class Solution:
def numRabbits(self, answers: List[int]) -> int:
counter = collections.Counter(answers)
return sum([math.ceil(v / (k + 1)) * (k + 1) for k, v in counter.items()])
class Solution {
public int numRabbits(int[] answers) {
Map<Integer, Integer> counter = new HashMap<>();
for (int e : answers) {
counter.put(e, counter.getOrDefault(e, 0) + 1);
}
int res = 0;
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
int answer = entry.getKey(), count = entry.getValue();
res += (int) Math.ceil(count / ((answer + 1) * 1.0)) * (answer + 1);
}
return res;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。