가운데 one+=one의 부분이 시간복잡도가 높은것같다. 쓰면안되는코드방식인가보다.
func solution(_ answers:[Int]) -> [Int] {
var one = [1,2,3,4,5]
var two = [2, 1, 2, 3, 2, 4, 2, 5]
var three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
var result:[Int] = [Int]()
// let numberOfAnswers = answers.count
//
// let oneNumbers = (numberOfAnswers / 5) + 1
// let twoNumbers = (numberOfAnswers / 8) + 1
// let threeNumbers = (numberOfAnswers / 10) + 1
// var oneArray = one.append(contentsOf: [])
for index in 0..<10{
one += one
}
for index in 0..<12{
two += two
}
for index in 0..<100{
three += three
}
var oneAnswer = 0
var twoAnswer = 0
var threeAnswer = 0
for (index,number) in answers.enumerated() {
if number == one[index]{
oneAnswer += 1
}
if number == two[index]{
twoAnswer += 1
}
if number == three[index]{
threeAnswer += 1
}
}
var order : [Int] = [Int]()
order = [oneAnswer,twoAnswer,threeAnswer]
var dic : Dictionary<Int,Int> = [:]
order.enumerated().map { (index,int) in
dic[index+1] = int
}
// dic
var sortedDic = dic.sorted { $0.value < $1.value
}
//sortedDic
// sortedDic = sortedDic.sorted(by: {
// $0.key < $1.key
// })
// sortedDic
var tmpSortedDic = sortedDic
for (index,number) in tmpSortedDic.enumerated() {
if index < 2 {
print("index:\(index)")
if number.value <= tmpSortedDic[index+1].value{
sortedDic.removeFirst() }
}
}
//sortedDic
//tmpSortedDic
if tmpSortedDic[0].value == tmpSortedDic[1].value {
if tmpSortedDic[1].value == tmpSortedDic[2].value {
result = [1,2,3]
return result
}
}
if tmpSortedDic[1].value == tmpSortedDic[2].value {
sortedDic = [tmpSortedDic[1],tmpSortedDic[2]].sorted(by: {$0.key < $1.key})
}
result = sortedDic.map { (key: Int, value: Int) in
return key}
return result
}
수정한 코드:
func solution(_ answers:[Int]) -> [Int] {
var a = [1, 2, 3, 4, 5] // index % 5
var b = [2, 1, 2, 3, 2, 4, 2, 5] // index % 8
var c = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
var diction = [1:0,2:0,3:0]
for (index,numer) in answers.enumerated() {
print(numer)
if a[index % 5] == numer {
diction[1] = diction[1]! + 1
}
if b[index % 8] == numer {
diction[2] = diction[2]! + 1
}
if c[index % 10] == numer {
diction[3] = diction[3]! + 1
}
}
print(diction)
var result = diction.filter { $0.value == diction.values.max()
}
.map { $0.key
}
.sorted(by: <)
return result
}