첫 번째 방법은 중복 방지를 위해 배열에서
contains
로 계속해서 확인해주었다. 시간 초과는 나지 않았지만, 생각보다 비효율적이라는 생각이 들어 1. 이름을 키 값으로 한 배열 인덱스를 리턴하는 딕셔너리를 생성, 2. 해당 인덱스로 접근 가능한 집합 배열을 만들었다.
import Foundation
func solution(_ id_list:[String], _ report:[String], _ k:Int) -> [Int] {
var reportDict = [String : [String]]()
var reportCntDict = [String : Int]()
var reportNames = Set<String>()
for r in report {
let r = r.split(separator: " ").map{String($0)}
let (reporter, reported) = (r[0], r[1])
let reportList = reportDict[reporter] ?? []
if !reportList.contains(reported) {
reportDict[reporter] = reportList + [reported]
let reportCnt = reportCntDict[reported] ?? 0
reportCntDict[reported] = reportCnt + 1
if reportCnt + 1 >= k {
reportNames.insert(reported)
}
}
}
var answers = [Int]()
for reporter in id_list {
let reportList = reportDict[reporter] ?? []
let reportListSet = Set(reportList)
let reportCnt = reportListSet.intersection(reportNames).count
answers.append(reportCnt)
}
return answers
}
import Foundation
func solution(_ id_list:[String], _ report:[String], _ k:Int) -> [Int] {
var nameDict = [String:Int]()
for item in id_list.enumerated() {
nameDict[item.element] = item.offset
}
var reportInfo = Array(repeating: Set<Int>(), count: id_list.count)
for r in report {
let r = r.split(separator: " ").map{String($0)}
let (reporter, reported) = (nameDict[r[0]]!, nameDict[r[1]]!)
reportInfo[reporter].insert(reported)
}
var reportList = Array(repeating: 0, count: id_list.count)
for report in reportInfo {
for id in report {
reportList[id] += 1
}
}
var reportResult = Set<Int>()
for idx in 0..<reportList.count {
let reportCnt = reportList[idx]
if reportCnt >= k {
reportResult.insert(idx)
}
}
var answers = [Int]()
for report in reportInfo {
let cnt = report.intersection(reportResult).count
answers.append(cnt)
}
return answers
}