781 Rabbits in the Forest (Dictionary Count)

1. Problem description:

In the forest, every rabbit has a color. Some of these rabbits (maybe all) tell you how many other rabbits have the same color as yourself. We put these answers in the answers array. Return the minimum number of rabbits in the forest.

Example:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
Two rabbits who answered "1" may have the same color, set to red.
The rabbits who answered "2" afterwards will not be red, otherwise their answers will contradict each other.
Let the rabbit that answered "2" be blue.
In addition, there should be two other blue rabbits in the forest whose answers are not included in the array.
So the minimum number of rabbits in the forest is 5: 3 answered and 2 unanswered.
Input: answers = [10, 10, 10]
Output: 11
Input: answers = []
Output: 0

Description:

  1. answers The maximum length is 1000.
  2. answers[i] Is [0, 999] an integer in the  range

Source: LeetCode
Link: https://leetcode-cn.com/problems/rabbits-in-forest

2. Thinking analysis:

By analyzing the questions, we can know that we might as well think like this. For the current answers[i] traversed, for example, the current answers[i] = n, there are at most n numbers in the answers equal to n, indicating that their colors are the same, if more than n Then it is another color, so you only need to use the dictionary to count the number of times each number appears. When it is found that the number currently traversed exists in the dictionary, then the number of times corresponding to the number in the dictionary should be reduced by 1, if it does not exist, then save Go into the dictionary, and add i + 1 to the result to indicate how many rabbits are of the same color. After thinking about it clearly, it’s actually a relatively easy solution.

3. The code is as follows:

import collections
from typing import List


class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        # 使用字典进行计数即可
        dic = collections.defaultdict(int)
        res = 0
        for i in answers:
            if dic[i]:
                dic[i] -= 1
            else:
                dic[i] = i
                res += i + 1
        return res

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/115310857