알고리즘/알고리즘 문제풀이

해쉬_Leetcode_rabbits-in-forest

Downey 2021. 8. 25. 14:35

https://leetcode.com/problems/rabbits-in-forest/submissions/

 

Rabbits in Forest - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

접근 방법

1. answers의 각 요소를 key로 사용하여, 각 요소가 몇 개 있는지 dict에 저장.

2. dict의 요소를 순회하며, 로직 수행.

3. key는 자신 외에 같은 색의 토끼가 몇 마리 있는지 이므로, + 1 하여 dict.key와 비교.

4. .key + 1 과 .value 가 같은 경우, 해당 색의 토끼가 모두 answer한 경우.

5. .key + 1 이 .value 보다 클 경우, 같은 색의 토끼가 전부 대답하진 않았지만, 일부는 대답한 경우.

6. .key + 1 이 .value 보다 작을 경우, 몫 = value/key+1을 수행. 몫의 값 만큼 같은 색의 그룹이 있다고 판단. 나머지 값 만큼 같은 색의 토끼가 전부 대답하지 않고 일부가 answer 했다고 간주.

정답 코드

Runtime: 16 ms, faster than 75.00% of Swift online submissions for Rabbits in Forest.

Memory Usage: 14.3 MB, less than 25.00% of Swift online submissions for Rabbits in Forest.

더보기
class Solution {
    func numRabbits(_ answers: [Int]) -> Int {
        var colorDict: [Int:Int] = [:]
        var sol = 0
        
        for answer in answers {
            if colorDict[answer] == nil {
                colorDict[answer] = 1
            } else {
                colorDict[answer]! += 1
            }
        }
        
        for color in colorDict {
            if color.key + 1 == color.value {
                sol += color.value
            }
            
            if color.key + 1 < color.value {
                let multiple = color.value / (color.key + 1)
                let remains = color.value % (color.key + 1)
                
                sol += multiple * (color.key + 1)
                if remains != 0 {
                    sol += color.key + 1
                }
            }
            
            if color.key + 1 > color.value {
                sol += color.key + 1
            }
        }
     
        return sol
    }
}