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) {
const answer = [];
commands.forEach(command => {
const arrayCommand = array.slice(command[0]-1, command[1]);
arrayCommand.sort((a,b) => a - b);
answer.push(arrayCommand[command[2]-1]);
})
return answer;
}
풀이방법
Array.silce()이용해서 풀이
- arrayCommand: slice() 메서드를 이용해 array에서 필요한 부분을 자른다.
- 잘라낸 배열을 arrayCommand를 오름차순으로 정렬
- 정렬한 배열에서 K번째 수를 answer에 push
- forEach무이 완료되면 answer를 return함.
'알고리즘 > 문제풀이' 카테고리의 다른 글
이진트리) Maximum Depth of Binary Tree [js] (0) | 2021.08.27 |
---|---|
프로그래머스 모의고사 javascript (0) | 2021.08.21 |
hash(level2) - 위장 (0) | 2021.08.14 |
완주하지 못한 선수 JS, javascript (0) | 2021.08.14 |
알고리즘 스터디 1주차 (0) | 2021.08.06 |