Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- TMDB
- 폰트
- ios
- dfs
- 프로그래머스
- SF 폰트
- LeetCode
- SwiftUI
- 알고리즘
- ios13
- Xcode
- 개발후기
- FSCalendar
- switch
- API
- flatMap
- optional
- Crashlytics
- viewcontroller
- Swift
- 회고록
- Realm
- Firebase
- RxSwift
- struct
- http
- typecasting
- enum
- swipe
- Lifecycle
Archives
- Today
- Total
Jerry's Bakery
[알고리즘] 신고 결과 받기(프로그래머스) 본문
문제 링크
코드
func solution(_ id_list:[String], _ report:[String], _ k:Int) -> [Int] {
var dic = [String:Int]()
var reportList: [[String]] = Array(repeating: [], count: id_list.count)
var result = Array(repeating: 0, count: id_list.count)
for i in id_list.indices {
dic.updateValue(i, forKey: id_list[i])
}
let set = Set(report)
let array = Array(set)
array.forEach {
let data = $0.split(separator: " ").map{ String($0) }
let from = data[0]
let to = data[1]
reportList[dic[to]!].append(from)
}
reportList.forEach {
if $0.count >= k {
$0.forEach {
result[dic[$0]!] += 1
}
}
}
return result
}
풀이
딕셔너리를 이차원 배열의 인덱스로 활용했습니다.
var dic = [String:Int]()
for i in id_list.indices {
dic.updateValue(i, forKey: id_list[i])
}
입력된 id_list가 ["muzi", "frodo", "apeach", "neo"] 였을 때 아래처럼 인덱스를 딕셔너리의 value값에 에 할당했습니다.
key | muzi | frodo | apeach | neo |
value | 0 | 1 | 2 | 3 |
유저에게 신고한 유저 정보를 담고 있는 2차원 배열을 선언합니다.
var reportList: [[String]] = Array(repeating: [], count: id_list.count)
각 유저는 한 번에 한 명의 유저를 신고할 수 있기 때문에 Set을 사용해 중복을 제거합니다.
그 후 각 유저에게 신고한 사람들을 추가합니다.
let set = Set(report)
let array = Array(set)
array.forEach {
let data = $0.split(separator: " ").map{ String($0) }
let from = data[0]
let to = data[1]
reportList[dic[to]!].append(from)
}
만약 report 배열이 ["muzi frodo", "apeach frodo", "frodoneo", "muzineo", "apeachmuzi"]와 같다면 reportList 배열은 아래와 같은 결과가 나오게 될 것입니다.
신고받은 유저 | 신고한 유저 | |
muzi[0] | apeach | |
frodo[1] | muzi | apeach |
apeach[2] | ||
neo[3] | frodo | muzi |
그 후 결괏값을 리턴하는 array 배열 선언 후 reportList를 순회하면서 k번 이상 신고를 당한 유저가 있다면 메일을 받도록 result배열에 추가합니다.
var result = Array(repeating: 0, count: id_list.count)
reportList.forEach {
if $0.count >= k {
$0.forEach {
result[dic[$0]!] += 1
}
}
}
만약 k가 2라면 frodo와 neo는 각각 2번 신고를 받았기 때문에 frodo와 neo에게 신고한 muzi, apeach frodo가 메일을 받게 될 것이고, result 배열은 [2, 1, 1, 0]이 될 것입니다.
'알고리즘' 카테고리의 다른 글
[알고리즘] Merge Two Sorted Lists(LeetCode) - Swift (0) | 2022.03.27 |
---|---|
[알고리즘] 양궁 대회(프로그래머스) (0) | 2022.03.18 |
Comments