• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

이렇게 풀어도 괜찮을까요?

23.05.29 21:02 작성 조회수 179

0

function solution (arr)

{

    let answer = [];

    let count = 1;

    for(i=0; i<arr.length; i++)

    {

        let max = Math.max(...arr);

   

        for(j=0; j<arr.length; j++)

        {

            if(arr[j] === max && arr[j] !== 0){

                answer[j] = count;

                arr[j] = 0;
                if(Math.max(...arr) !== max) count++;                           }    

        }   

}
    return answer;

}  

답변 1

답변을 작성해보세요.

0

안녕하세요^^

위에 코드는 정답이 나오지 않는 코드입니다. 만약

let arr = [90, 90, 80, 80, 70];

이라면 정답은 [1, 1, 3, 3, 5] 가 답입니다.

코드 개선해 보았습니다.

function solution (arr){
    let answer = [];
    let count = 1;
    for(i=0; i<arr.length; i++){
        let max = Math.max(...arr);
        let cnt = 0;
        for(j=0; j<arr.length; j++){
            if(arr[j] === max && arr[j] !== 0){
                answer[j] = count;
                arr[j] = 0;
                cnt++;
            }    
        }  
        count+=cnt;
    }
    return answer;
}