프로그래머스 - k번째수 (아니 도대체 뭐가다른겨?)

KIMMY·2020년 7월 3일
0

코딩테스트연습

목록 보기
6/7

프로그래머스 lv.1 - 정렬 - k번째 수

처음엔 filter을 이용 -> 2/4 번째 케이스에서 오류가났다.

그래서 slice로 변경 -> 됨....

사실 같은 방식인데 뭐가다른지 모르겠DA!!!

  1. filter -> 안됨 ^_^;;
function solution(array, commands) {
    var answer = [];
    for (let i=0; i<commands.length; i++){
        let from = commands[i][0]-1;
        let to = commands[i][1]-1;
        let index = commands[i][2]-1;
        let filteredArr = array.filter(e => 
                        (array.indexOf(e) >= from && array.indexOf(e) <= to));
        filteredArr.sort((a,b)=>a-b);
        answer[i]= filteredArr[index] ? filteredArr[index] : null;
    }
    return answer;
}

-> index 부분을 바꿨더니 된다.(아래처럼)

let filteredArr = array.filter((e,IndexOfe) => 
                        (IndexOfe >= from && IndexOfe <= to));

-> 내 추측으로는 / 기존의 array.indexOf(e) 방식은
array에서 '첫'번째로 같은녀석을 찾는데, 중복된 숫자가 있거나,
혹은 없어서..(?) -1이 나온게 아닐까 싶다.

궁금하다.. 케이스.. 그리고 물어볼 사람이 없다는 것은.. 슬프다

  1. slice
function solution(array, commands) {
    var answer = [];
    for (let i=0; i<commands.length; i++){
        let start = commands[i][0]-1;
        let end = commands[i][1];
        let one = (start === end) ? start : null;
        let index = commands[i][2]-1;
        let filteredArr = one ? array.slice(one) : array.slice(start,end);
        answer.push(filteredArr.sort((a,b)=>a-b)[index]);
    }
    return answer;
}
  1. 내 생각에 멋진 답 (다른사람이 한것)
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]
    })
}

특히... const [sPosition, ePosition, position] = command
부분이 좋다. 공부를 더해야겠다.

profile
SO HUMAN

0개의 댓글