[프로그래머스] 실패율

쿼카쿼카·2023년 1월 15일
0

알고리즘

목록 보기
29/67

코드

function solution(N, stages) {
    const result = [];
    
    // 내가 푼 풀이
    const arr = [];
    const accStage = [];
    const totalMember = stages.length;
    stages.sort((a,b) => a-b)
    
    for(let i=0; i<N; i++) {
        const stageMember = stages.filter(x => x === i+1).length;
        arr.push(stageMember);
        if(i === 0) {
            accStage.push(stageMember);
            result.push({ [i+1]: arr[i] / totalMember})
        }
        else {
            accStage.push(accStage[i-1] + stageMember);
            result.push({ [i+1]: arr[i] / (totalMember - accStage[i-1])});
        }
    }
    return result.sort((a, b) => Object.values(b) - Object.values(a)).map(x => parseInt(Object.keys(x)));
    
    // 다른 사람 풀이 참고해서 다시 푼 풀이
    for(let i=0; i<N; i++) {
        const cur = stages.filter(x => x === i+1).length;
        const reachNum = stages.filter(x => x >= i+1).length;
        result.push([i+1, cur/reachNum]);
    }
    return result.sort((a, b) => b[1] - a[1]).map(x => x[0]);
}

배운 점

  • get 할 때 시간 복잡도가 O(1)이라 생각해서 객체로 줬더니 짧은 식보다 조금 더 빨라서 겁나게 뿌듯하다^^
  • 다만 식을 쓸 때 조금 더 간추릴 수 있는 방법을 찾아 줄여보자
profile
쿼카에요

0개의 댓글