티스토리 뷰
문제 : 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) {
var answer = [];
commands.forEach( el => {
let result = array.slice(el[0]-1, el[1]).sort(function(a, b){
return a - b
})
answer.push(result[el[2]-1])
})
return answer;
}
array.slice 메서드를 사용하여 i번째부터 j번째까지 선택을 했다. 그뒤, .sort 메서드를 사용하여 정렬을 하였고, 택한을 한 배열의 n 번째 요소를 선택하여 배열을 리턴했다.
다른 사람의 풀이 :
function solution(array, commands) {
return commands.map(command => {
const [sPosition, ePosition, position] = command
const newArray = array
.filter((value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1)
.sort((a,b) => a - b)
return newArray[position - 1]
})
}
먼저 commands.map 메서드를 이용하여 결과 값들을 배열로 반환하기 때문에 따로 answer = [] 와 같은 배열을 만들 필요가 없었다. 그리고 filter 메서드를 사용하여 .slice 메서드를 역할을 대신 수행하였다.
'프로그래머스 > 코딩테스트' 카테고리의 다른 글
프로그래머스 문제풀기 #없는 숫자 더하기 (0) | 2021.11.26 |
---|---|
프로그래머스 문제 풀기 #신규 아이디 추천 (0) | 2021.11.26 |
프로그래머스 문제 풀기 #숫자 문자열과 영단어 (0) | 2021.11.26 |
댓글