https://school.programmers.co.kr/learn/courses/30/lessons/178871
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
blog/modules/code-test/src/main/kotlin/com/example/blog/level1/0009_달리기 경주.kt at develop · shyeom1023/blog
블로그 게시물을 위한 테스트 코드 및 자료 모음. Contribute to shyeom1023/blog development by creating an account on GitHub.
github.com
달리기 경주
얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe" 선수가 1등, "mumu" 선수가 2등으로 바뀝니다.
선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players
와 해설진이 부른 이름을 담은 문자열 배열 callings
가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.
제한사항
- 5 ≤
players
의 길이 ≤ 50,000players[i]
는 i번째 선수의 이름을 의미합니다.players
의 원소들은 알파벳 소문자로만 이루어져 있습니다.players
에는 중복된 값이 들어가 있지 않습니다.- 3 ≤
players[i]
의 길이 ≤ 10
- 2 ≤
callings
의 길이 ≤ 1,000,000callings
는players
의 원소들로만 이루어져 있습니다.- 경주 진행중 1등인 선수의 이름은 불리지 않습니다.
입출력 예
players | callings | result |
---|---|---|
["mumu", "soe", "poe", "kai", "mine"] | ["kai", "kai", "mine", "mine"] | ["mumu", "kai", "mine", "soe", "poe"] |
입출력 예 설명
입출력 예 #1
4등인 "kai" 선수가 2번 추월하여 2등이 되고 앞서 3등, 2등인 "poe", "soe" 선수는 4등, 3등이 됩니다. 5등인 "mine" 선수가 2번 추월하여 4등, 3등인 "poe", "soe" 선수가 5등, 4등이 되고 경주가 끝납니다. 1등부터 배열에 담으면 ["mumu", "kai", "mine", "soe", "poe"]이 됩니다.
알게된 점
처음 문제를 풀었을때는 indexOf
를 사용 했다. 그러나 대상자가 많아지면 indexOf
를 사용하면 O(n)
의 시간 복잡도를 가지는 것을 알게 되었다.
이때 해결 할 수 있는 방법이 index를 맵핑한 MutableMap
을 사용하면 시간 복잡도가 O(1)
된다는 것을 알게 되었다.
package com.example.blog.level1
fun main(args: Array<String>) {
val friends: Array<String> =
arrayOf("mumu", "soe", "poe", "kai", "mine")
val gifts: Array<String> =
arrayOf("kai", "kai", "mine", "mine")
val result = Solution9().solution(friends, gifts)
// println("result : $result")
result.forEach { println(it) }
}
private class Solution9 {
fun solution(players: Array<String>, callings: Array<String>): Array<String> {
var answer: Array<String> = arrayOf<String>()
val associate = players.withIndex().associate { it.value to it.index }.toMutableMap()
callings.forEach {
val index = associate[it]!!
val p = players[index - 1]
associate[p] = index
associate[it] = index -1
players[index - 1] = it
players[index] = p
}
answer = players
return answer
}
}
'코딩 공부 > 코딩테스트-level1' 카테고리의 다른 글
[코딩테스트] Level1 - 바탕화면 정리 (0) | 2024.07.28 |
---|---|
[코딩테스트] Level1 - 공원 산책 (3) | 2024.07.25 |
[코딩테스트] Level1 - 가장 많이 받은 선물 (3) | 2024.07.24 |
[코딩테스트] Level1 - 푸드 파이트 대회 (0) | 2024.07.22 |
[코딩테스트] Level1 - 추억 점수 (0) | 2024.07.19 |