백준_2910_Hash

hankyulee·2022년 5월 21일
0

Swift coding test 준비

목록 보기
53/57

Replacing if-else statements with the short code reduces the liens of code. But it takes longer than before.

let given = readLine()!.split(separator: " ").map{Int(String($0))!}
let array = readLine()!.split(separator:" ").map{Int(String($0))!}

var dict : [Int:[Int]] = [:]
let n = given[0]
let m = given[1]
for i in 0..<n {
    let index = array[i]
    dict[index] = (dict[index] ?? [i,0])
    dict[index]![1] += 1
}

//let sortedDict = dict.sorted { a, b in
//
//    if a.value[1] == b.value[1] {
//        return a.value[0] < b.value[0]
//    }
//    else {
//        return a.value[1] > b.value[1]
//    }
//}


let sortedDict = dict.sorted{$0.1[1] > $1.1[1] || $0.1[0] < $1.1[0]}

var result = [Int]()
for i in sortedDict {
    result += Array(repeating: i.key, count: i.value[1])
}

for i in result {
    print(i,terminator: " ")
}

풀이2, dict 2개

import Foundation
//
let given = readLine()!.split(separator: " ").map{Int(String($0))!}
let array = readLine()!.split(separator:" ").map{Int(String($0))!}
//
var dict : [Int:Int] = [:]
var dict2 : [Int:Int] = [:]
let n = given[0]
let m = given[1]
for i in 0..<n {
    let index = array[i]
    dict[index] = (dict[index] ?? 0)
    dict[index]! += 1
    dict2[index] = (dict2[index] ?? i)
}
let sortedDict = dict.sorted{$0.1 > $1.1 || ($0.1 == $1.1) && dict2[$0.0]! < dict2[$1.0]!}

var result = [Int]()
for i in sortedDict {
    result += Array(repeating: i.key, count: i.value)
}

for i in result {
    print(i,terminator: " ")
}

0개의 댓글