1. 程式人生 > >LeetCode 781. Rabbits in Forest

LeetCode 781. Rabbits in Forest

題解

這題很有意思。
想想,有兔子說有 x 個同色兔子,那麼其實就是說有 x+1 個兔子同色。
換言之,這個 x 最多可以在陣列中重複 x+1 次,但是顯然 x 可以出現任意次。
少於 x+1 就意味著有部分兔子沒說話,多餘則表示還有另外顏色的兔子
也有 x+1 個。
所以,此題用map記錄 x 的次數。然後算 (x+1) * ceil( map[x]/(x+1) )即可。


Code

public int numRabbits(int[] answers) {
        Map<Integer,Integer> map =new HashMap<
>(); int res=0; for(int a:answers){ map.put( a , map.getOrDefault(a,0)+1); } for(Integer n : map.keySet()){ int counts = map.get(n)/(n+1); res+= map.get(n)%(n+1) == 0? counts*(n+1) : (counts+1)*(n+1); } return
res; }