Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間7月前 (2025/04/20 14:28), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1399/1548 (看更多)
https://leetcode.com/problems/rabbits-in-forest/description 781. Rabbits in Forest 你走到一個森林裡問了n個兔子:「有幾個兔子和你是一樣顏色的peko」,這些答案表示 成 answers[i],依照答案找出這座森林裡最少有幾隻兔子。 思路: 1.對每個兔子給的答案分組,如果回答有i個兔子一樣顏色表示至少有i+1隻兔子,然後 如果有多個一樣的i表示有多個不同顏色一樣數量的兔子,向上取整就好。 Java Code: ------------------------------------------ class Solution { public int numRabbits(int[] answers) { int[] cnt = new int[1001]; for (int answer : answers) { cnt[answer]++; } int res = 0; for (int i = 0; i < cnt.length; i++) { if (cnt[i] == 0) continue; res += (i + 1) * ceil(cnt[i], (i + 1)); } return res; } private int ceil(int a, int b) { if (a % b == 0) { return a / b; } return a / b + 1; } } ------------------------------------------ -- https://i.imgur.com/yRXNquY.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.104.111 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1745130500.A.6C8.html
文章代碼(AID): #1e19G4R8 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1e19G4R8 (Marginalman)