728x90
Javascript
function getArray(a, c) {
let s = parseInt(c.slice(0,1));
let e = parseInt(c.slice(1,2));
let idx = parseInt(c.slice(-1));
let tmp = a.slice(s-1,e);
return tmp.sort((a, b) => a - b)[idx-1];
}
function solution(array, commands) {
let tmp_ans = [];
for (let i=0; i<commands.length;i++) {
tmp_ans.push(getArray(array, commands[i]));
}
return tmp_ans;
}
* js에서는 string to int 하려면, parseInt를 사용해야 한다.
* js에서는 slice 메서드를 사용해서 slicing해줘야 한다.
* js sort 메서드에서 테스트케이스를 통과하지 못하는 경우가 발생했다.
* 원인: If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array.
* 요약: compareFunction을 지정하지 않으면 숫자를 문자열로 바꿔서 정렬하기 때문에 숫자간 정렬이 필요할 경우에는 compareFunction을 사용하는 것이 중요하다.
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
shorter syntax ⬇
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
Python
def getArr(a,c):
# c = [int(x) for x in c]
a = a[c[0]-1:c[1]]
a.sort()
return a[c[2]-1]
def solution(array, commands):
answer = []
for com in commands:
answer.append(getArr(array, com))
return answer
from solution threads:
def solution(array, commands):
answer = []
for command in commands:
i,j,k = command
answer.append(list(sorted(array[i-1:j]))[k-1])
return answer
i,j,k를 각각 할당한다는 점이 좋았다. 보기 편하도록
728x90
'Algorithm' 카테고리의 다른 글
[프로그래머스] 2016년 (Python, JS) (0) | 2021.01.25 |
---|---|
[프로그래머스] 두 개 뽑아서 더하기 (JS, Python) (0) | 2021.01.25 |
[프로그래머스] 체육복 (javascript) (0) | 2021.01.23 |
[프로그래머스] 체육복 (python) (0) | 2021.01.18 |
[프로그래머스] 모의고사 (python, javascript) (0) | 2021.01.17 |
댓글