프로그래머스 Lv1. K번째수

용상윤·2021년 2월 26일
0

📌 문제

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


📌 접근

  • map()

📌 코드

js

처음 작성한 코드(for문 사용)

function solution(array, commands) {
    var answer = [];
    
    for(var i=0; i<commands.length; i++){
        var temp = array.slice(commands[i][0]-1, commands[i][1]);
        temp = temp.sort((a,b) => a-b);
        answer.push(temp[commands[i][2]-1]);
    }
    
    return answer;
}

map() 사용

function solution(array, commands) {
    return commands.map(command => {
        const [i, j, k] = command;
        return array.slice(i-1, j).sort((a,b) => a-b)[k-1];
    })
}

python

def solution(array, commands):
    result = []
    for command in commands :
        [i, j, k] = command
        result.append( sorted(array[i-1:j])[k-1] )
        
    return result

✍ 메모

  • js 오름차순 정렬
  • js, python 리스트 슬라이싱

오름차순 내림차순

const num = [2,5,7,1,3,6];
num.sort((a,b) => a-b);
// [1, 2, 3, 5, 6, 7]

num.sort((a,b) => b-a);
// [7, 6, 5, 3, 2, 1]

리스트 슬라이싱

[3,4,5] 를 출력하고 싶을 때

js

arr.slice(a, b)
a부터 b미만까지

const num = [1,2,3,4,5,6,7];
num.slice(2,5);
// [3,4,5]

python

arr[a:b]
a부터 b미만까지

num = [1,2,3,4,5,6,7]
num[2:5]
# [3,4,5]

profile
달리는 중!

0개의 댓글