TIL #12

loci·2024년 5월 12일
0

TIL

목록 보기
11/103


K번째수

배열다루는 문제
이중반복문으로 조건에 따라 인덱스로 배열의 값을 가져오고 다른 배열에 따로 추가해주고 sort()로 정렬해줌


나의 풀이

class Solution {
    fun solution(array: IntArray, commands: Array<IntArray>): IntArray {
        var answer = intArrayOf()
        for (i in commands){
            var result = intArrayOf()
            for(j in i[0]-1 until i[1]){
                result += array[j]
            }
            result.sort()
            answer += result[i[2]-1]
            
        }
        return answer
    }
}

다른사람의 풀이

class Solution {
        fun solution(array: IntArray, commands: Array<IntArray>): IntArray {
            return commands.map { command ->
                array.slice(IntRange(command[0] - 1, command[1] - 1)).sorted()[command[2] - 1]
            }
                .toIntArray()
        }
    }

map으로 command의 index에 가져와서 slice로 나눠준뒤 sorted()로 정렬하고 해당 값 반환하고 만들어진 컬렉션을 .toIntArray()로 IntArray로 변환

profile
편리한 개발자

0개의 댓글