본문 바로가기

알고리즘

[Hash] Rabbits in Forest - LeetCode Swift

문제 : https://leetcode.com/problems/rabbits-in-forest/

 

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

 

풀이방법

value % (key + 1) == 1 일 때, result에 key + 1(자신) 을 해준다.

첫번째 예시

  1. answers : [1] -> 1 % (1+1) == 1 이니까 result에 + 2

두번째 예시

answers : [1, 1] ->

  1. dic[1: 1] 일 때 -> 1 % (1+1) == 1 이니까 result에 + 2
  2. dic[1: 2] 일 때 -> 2 % (1+1) == 0 이니까 result에 아무것도 안함

세번째 예시

answers : [1, 1, 1] ->

  1. dic[1: 1] 일 때 -> 1 % (1+1) == 1 이니까 result에 + 2
  2. dic[1: 2] 일 때 -> 2 % (1+1) == 0 이니까 result에 아무것도 안함
  3. dic[1: 3] 일 때 -> 3 % (1+1) == 1 이니까 result에 + 2

 

코드

class Solution {
    func numRabbits(_ answers: [Int]) -> Int {
        var rabits = [Int:Int]()
        var result = 0
        
        for i in answers {
            if rabits[i] != nil {
                rabits[i]! += 1
            } else {
                rabits[i] = 1
            }
        
            if rabits[i]! % (i+1) == 1 {
                result += i+1
            }
            
            if i == 0 {
                result += 1
            }
        }
 
        return result 
    }
}
반응형