[Level 1] 프로그래머스 K번째 수 kotlin 풀이

[Level 1] 프로그래머스 K번째 수 kotlin 풀이

정렬! 프로그래머스 “K번째 수” 문제를 풀어보자


문제 소개

이번에 풀어볼 문제는 프로그래머스 코테 Level-1 K번째 수 라는 문제입니다!

kth_num_problem

이번 문제는 그냥 자르기 - 정렬 - 찾기 로 끝나는 간단한 문제로 보입니다.


문제 풀이

풀이도 간단합니다!

입력받은 array커멘드[0]에서 커멘드[1] 까지 slice 하면 되는데
우리는 zero-based-numbering을 사용하고있으니 1씩 빼서 범위를 잡습니다.

zero-based-numbering은 시작 index를 0으로 세는 indexing 방법을 이야기합니다.

그다음 kotlin 내장 정렬기능을 이용해서 정렬 후

정렬된 Int 배열에서 커멘드[2]에서 마찬가지로 1을 뺀 수를 index로 가지는 수를 가져와서 새로운 배열에 넣어 제출하면 되겠네요!


정답 코드

1번 코드

그래서 처음에 짠 코드는 이러합니다.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
fun solution(array: IntArray, commands: Array<IntArray>): IntArray {
var answer = intArrayOf()

commands.forEach {
answer += array.sliceArray((it[0] - 1) until it[1]).apply { sort() }[it[2] - 1]
}

return answer
}
}

여기서 python의 list comprehension이 떠올라서 다시 코드를 짜봤습니다.


2번 코드

1
2
3
4
class Solution {
fun solution(array: IntArray, commands: Array<IntArray>): IntArray =
commands.map { array.sliceArray((it[0] - 1) until it[1]).apply { sort() }[it[2] - 1] }.toIntArray()
}

끔찍한 원라이닝

이번엔 map기능을 이용하여 짜봤습니다!


문제는 금방 풀렸지만 pythonlist comprehension과 유사한 동작을 할 수 있는 방법을 찾아서 좋았습니다!

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

댓글