반응형
```
백준 1015번 수열 정렬 Kotlin 구현해 보기
```
이번 글을 통해 배워갈 내용
- 백준 1015번 수열 정렬 풀이
https://www.acmicpc.net/problem/1015
1015번: 수열 정렬
P[0], P[1], ...., P[N-1]은 0부터 N-1까지(포함)의 수를 한 번씩 포함하고 있는 수열이다. 수열 P를 길이가 N인 배열 A에 적용하면 길이가 N인 배열 B가 된다. 적용하는 방법은 B[P[i]] = A[i]이다. 배열 A가 주
www.acmicpc.net
백준 1015번 수열 정렬은
난이도 실버 등급의 문제로서
설명
수열을 오름차순으로 정렬하고
정렬된 수열에 위치를 기존 수열에 위치에 따라 출력해 주면 되는 문제입니다
예를 들어
기존수열 2 3 1
주소수열 1 2 0
정렬수열 1 2 3
1은 0 번째
2는 1번째
3은 2번째입니다
따라서 주소수열을 1 2 0 출력해 주면 됩니다.
30분 정도 위에 링크를 방문하셔서 풀어보시고
안 풀리시는 경우에만 아래 해답을 봐주시면 감사하겠습니다.
정렬을 해준 다음
rawNums 값들에 순차적으로 정렬된 값을 업데이트하고 idx를 받아와서 풀었습니다
fun main(args: Array<String>) {
val inputDto = getInput()
print(solution(inputDto))
}
fun getInput(): InputDto {
val numCnt = readln().toInt()
val rawNums = readln().split(" ").map { m -> m.toInt() }
return InputDto(rawNums)
}
data class InputDto(
val rawNums: List<Int>
)
fun findAddressNums(rawNums: List<Int>): List<Int> {
val sortedNums = rawNums.sorted().toMutableList()
return rawNums.map { num -> findAndRemoveIdx(sortedNums, num) }
}
private fun findAndRemoveIdx(sortedNums: MutableList<Int>, num: Int): Int {
val idx = sortedNums.indexOf(num)
sortedNums[idx] = -1
return idx
}
fun solution(dto: InputDto): String {
val addressNums = findAddressNums(dto.rawNums)
return addressNums.joinToString(" ")
}
// https://codemasterkimc.tistory.com/
테스트
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class MainKtTest {
@Test
fun test() {
assertEquals(
"2 1 0",
solution(
InputDto(listOf(3, 2, 1))
)
)
assertEquals(
"2 3 1 0",
solution(
InputDto(listOf(3, 3, 2, 1))
)
)
assertEquals(
"4 0 6 1 3 7 2 5",
solution(
InputDto(listOf(4, 1, 6, 1, 3, 6, 1, 4))
)
)
}
}
읽어주셔서 감사합니다
무엇인가 얻어가셨기를 바라며
오늘도 즐거운 코딩 하시길 바랍니다 ~ :)
728x90
반응형
'Kotlin > Kotlin 알고리즘' 카테고리의 다른 글
백준 20291번 파일정리 Kotlin 구현해보기 (0) | 2023.03.11 |
---|---|
백준 11652번 카드 Kotlin 구현해보기 (0) | 2023.03.11 |
백준 1182번 부분수열의 합 Kotlin 구현해보기 (0) | 2023.03.11 |
백준 9663번 N-Queen Kotlin 구현해보기 (0) | 2023.03.10 |
백준 14888번 연산자 끼워넣기 Kotlin 구현해보기 (0) | 2023.03.10 |