📝 알고리즘/Programmers

[Javascript/PGS] Lv.2 : 귤 고르기

xxilliant 2025. 4. 7. 10:38
728x90
반응형

 

https://school.programmers.co.kr/learn/courses/30/lessons/138476#

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


프로그래머스 레벨 2.

종류 갯수를 카운팅할 때 신경써야할 부분(경우)이 좀 있고,

sort도 신경써줘야 한다 ㅋ.....ㅋ

 

JS의 sort()는 문자열 기준이기 때문에, 숫자를 제대로 비교하고 정렬하려면 반드시 비교 함수를 넣어줘야 한다!!!

 

 

 

나의 풀이

function solution(k, tangerine) {
    var answer = 0;
    let tmap = new Map();
    tangerine.forEach((t)=>{
        if(tmap.has(t)) tmap.set(t,tmap.get(t)+1);
        else tmap.set(t,1);
    })
    let countList = [];
    tmap.forEach((val, key)=>{
        countList.push([val, key]);
    })
    countList.sort((a,b)=> b[0]-a[0]);
    
    let toEnd = false;
    for(let i=0; i<countList.length; ++i){
        if(k-countList[i][0] < 0) break;
        if(i===countList.length-1) toEnd = true;
        k -= countList[i][0];
        answer ++;
    }
    if(k>0 && !toEnd) answer ++;
    return answer;
}

 

728x90
반응형