Skip to content

Commit f27d998

Browse files
committed
781. rabbits in forest
1 parent 714da3e commit f27d998

File tree

1 file changed

+28
-0
lines changed
  • medium/0781-rabbits-in-forest

1 file changed

+28
-0
lines changed

medium/0781-rabbits-in-forest/sol.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <vector>
2+
#include <unordered_map>
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int numRabbits(vector<int>& answers) {
8+
unordered_map<int,int> counts;
9+
int rabbits = 0;
10+
11+
for(int i=0;i<answers.size();i+=1) {
12+
int ans = answers[i];
13+
14+
// if in counts, decrease and move with next one
15+
if(counts.find(ans)!=counts.end() && counts[ans] > 0) {
16+
counts[ans] -= 1;
17+
}
18+
19+
// if not accounted, increase rabbits by 1 + num[i]
20+
else {
21+
counts[ans] = ans;
22+
rabbits += 1 + ans;
23+
}
24+
}
25+
26+
return rabbits;
27+
}
28+
};

0 commit comments

Comments
 (0)