Q38 Rabbits in Forest - LeetCode
Fri Jan 27 2023 14:59:04 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
class Solution {
public int numRabbits(int[] answers) {
//make a HM to store <answers of rabits , actual rabits>
HashMap<Integer,Integer> map = new HashMap<>();
int ans = 0;
for(int val : answers){
//if that answer already exists, might mean that rabbit belongs to same colour
if(map.containsKey(val)){
//if already that color of rabbits is 0 and still the answer is same means there might be same no. of rabits of different color , so we remove the old color store the answer and add the new color group
if(map.get(val) == 0){
ans += val+1;
map.put(val , val);
}
//if answer already exists and there is frequency left,means that rabbit also belong to that same colour and he will take one spot and decrement frequency
else{
map.put(val , map.get(val)-1);
}
}
//if answer doesn't already exists means its a new color of rabit
else{
map.put(val , val);
}
}
//now add all (keys + 1) values in the answer as while mapping the colour to frequency we already take into account the spot of the rabbit which is giving the answer
for(int val : map.keySet())
ans += val+1;
return ans;
}
}
content_copyCOPY
https://leetcode.com/problems/rabbits-in-forest/
Comments