-
[Programmers] Lv1. 달리기 경주(Kotlin)SW Test/Programmers 2023. 4. 11. 01:40반응형
문제
예시
풀이
- Hash (map)을 사용하지 않더라도 답을 구할 수는 있습니다. callings에 나온 문자열에 해당하는 index를 indexOf 함수를 이용해서 직접 찾고 이전 값과 swap을 하면 됩니다.
- 하지만 이 경우 시간복잡도는 callings가 1,000,000 이고 players가 50,000 이여서 시간 초과가 불가피합니다.
- 따라서 빠른 검색이 가능한 mutableMapOf 함수를 사용하여 index만 빠르게 가져온 후 value 값을 변경하면 됩니다.
- 참고로 mutableMapOf는 LinkedHashMap을 생성하는 함수로 HashTable 형태로 구현되어 있으며 Double Linked로 Entry를 관리하여 순서도 보장됩니다.
class Solution { fun solution(players: Array<String>, callings: Array<String>): Array<String> { val map = mutableMapOf<String, Int>().apply{ players.forEachIndexed{ index, player -> put(player, index) } } callings.forEach{ var index = map[it]!! val temp = players[index-1] map[it] = index - 1 map[temp] = index players[index-1] = players[index] players[index] = temp } return players } }
참고
- 함수형 프로그래밍 언어인 kotlin의 특성에 맞게 함수를 많이 익히자 😽
- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-linked-hash-map/
LinkedHashMap - Kotlin Programming Language
kotlinlang.org
반응형'SW Test > Programmers' 카테고리의 다른 글
[Programmers] Lv1. 바탕화면 정리(Kotlin) (0) 2023.04.26 [Programmers] Lv1. 추억점수(kotlin) (0) 2023.04.13 [Programmers] Lv2.모음사전(kotlin) (0) 2022.10.22 [Programmers] Lv2. 연속 부분 수열(kotlin) (0) 2022.10.22 [Programmers] Lv2. 피로도(kotlin) (0) 2022.10.22