You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0700-0799/0781.Rabbits in Forest/README_EN.md
+74-11
Original file line number
Diff line number
Diff line change
@@ -58,7 +58,13 @@ The smallest possible number of rabbits in the forest is therefore 5: 3 that ans
58
58
59
59
<!-- solution:start -->
60
60
61
-
### Solution 1
61
+
### Solution 1: Greedy + Hash Map
62
+
63
+
According to the problem description, rabbits that give the same answer may belong to the same color, while rabbits that give different answers cannot belong to the same color.
64
+
65
+
Therefore, we use a hash map $\textit{cnt}$ to record the number of occurrences of each answer. For each answer $x$ and its occurrence $v$, we calculate the minimum number of rabbits based on the principle that each color has $x + 1$ rabbits, and add it to the answer.
66
+
67
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\textit{answers}$.
62
68
63
69
<!-- tabs:start -->
64
70
@@ -67,26 +73,83 @@ The smallest possible number of rabbits in the forest is therefore 5: 3 that ans
67
73
```python
68
74
classSolution:
69
75
defnumRabbits(self, answers: List[int]) -> int:
70
-
counter = Counter(answers)
71
-
returnsum([math.ceil(v / (k +1)) * (k +1) for k, v in counter.items()])
76
+
cnt = Counter(answers)
77
+
ans =0
78
+
for x, v in cnt.items():
79
+
group = x +1
80
+
ans += (v + group -1) // group * group
81
+
return ans
72
82
```
73
83
74
84
#### Java
75
85
76
86
```java
77
87
classSolution {
78
88
publicintnumRabbits(int[] answers) {
79
-
Map<Integer, Integer>counter=newHashMap<>();
80
-
for (inte: answers) {
81
-
counter.put(e, counter.getOrDefault(e, 0) +1);
89
+
Map<Integer, Integer>cnt=newHashMap<>();
90
+
for (intx: answers) {
91
+
cnt.merge(x, 1, Integer::sum);
82
92
}
83
-
int res =0;
84
-
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
85
-
int answer = entry.getKey(), count = entry.getValue();
0 commit comments