문제 : https://leetcode.com/problems/rabbits-in-forest/
풀이방법
value % (key + 1) == 1 일 때, result에 key + 1(자신) 을 해준다.
첫번째 예시
- answers : [1] -> 1 % (1+1) == 1 이니까 result에 + 2
두번째 예시
answers : [1, 1] ->
- dic[1: 1] 일 때 -> 1 % (1+1) == 1 이니까 result에 + 2
- dic[1: 2] 일 때 -> 2 % (1+1) == 0 이니까 result에 아무것도 안함
세번째 예시
answers : [1, 1, 1] ->
- dic[1: 1] 일 때 -> 1 % (1+1) == 1 이니까 result에 + 2
- dic[1: 2] 일 때 -> 2 % (1+1) == 0 이니까 result에 아무것도 안함
- 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
}
}
반응형
'알고리즘' 카테고리의 다른 글
[프로그래머스] 배열의 원소 삭제하기 (6) | 2023.10.12 |
---|---|
이진탐색 - Swift (0) | 2022.02.19 |
[BFS] 음식물 피하기 - baekjoon Swift (2) | 2021.08.24 |
[DFS] N과 M - baekjoon Swift (0) | 2021.08.23 |
[투포인터] Container With Most Water - LeetCode Swift (2) | 2021.08.18 |