알고리즘/프로그래머스 - JS

[프로그래머스-JS] level.1 k번째수 <정렬>

개발자성장기 2022. 6. 30. 00:27
반응형

https://programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

 

 

나의 코드 

 

function solution(array, commands) {
   let classify
   let box = []
    for(i=0; i < commands.length; i++){
        let start = commands[i][0]
        let end = commands[i][1]
        let choice = commands[i][2]
         classify = array.slice(start - 1,end ).sort((a,b) => a-b)
         box.push(classify[choice-1])
    }
 
    return box;
}

 

 

처음에 그냥 sort() 만 해줬는데 오류가 났다. 

알고 보니 정렬이 문제였다. 

그래서 오름차순으로 하기위해  sort((a,b) => a - b) 로 바꾸었다

 

여기서 조금 더 이쁘게 할려면 구조분해할당을 쓰면된다.

 

 

function solution(array, commands) {
   let classify
   let box = []
    for(i=0; i < commands.length; i++){
        let [start, end, choice] = commands[i]
         classify = array.slice(start - 1,end ).sort((a,b) => a-b)
         box.push(classify[choice-1])
    }
 
    return box;
}

 

 

다른 사람 풀이 보고 응용

 

const solution = (array, commands) => commands.map(
([start, end, choice]) => array.slice(start - 1, end).sort((a,b) => a-b)[choice-1])

map으로 할 수도 있다. 

그리고 map할때 바로 디스트럭처링을 하면 훨씬 가독성이 좋아진다.

반응형