[프로그래머스 | JS] LV.1 체육복

Urther·2022년 8월 4일
0

알고리즘

목록 보기
39/41
post-thumbnail

Problem | 체육복

✨ 접근 방식

여벌 체육복을 가져온 학생이 체육복을 도난당했을 수 있습니다. 이때 이 학생은 체육복을 하나만 도난당했다고 가정하며, 남은 체육복이 하나이기에 다른 학생에게는 체육복을 빌려줄 수 없습니다.

이 문장을 해석하지 못해서 여러 번 틀렸다.

  1. 가장 먼저 고려해야하는 것은 자신의 체육복이 분실되었고, 여분의 체육복이 있다면 자신 먼저 고려해야한다는 것이다.
  2. reserve를 탐색할 때 sort 되어있어야 한다.
  • 해당 반례 ) n=5, lost=[2,4] , reserve=[3,1]
  • 만약 [3,1] 대로 탐색한다면 3이 2를 먼저 차지할 것이다.

- ✔️ 전체코드

function solution(n, lost, reserve) {
    var answer = 0;
    
    const student=new Array(n+1).fill(true);
    let count=0;
    
    for(let x of lost){
        const index=reserve.indexOf(x);
        if(index!==-1){
            const prev=reserve.slice(0,index);
            const next=reserve.slice(index+1);
            reserve=[...prev,...next]
            continue;
        }
        student[x]=false;
        count++;
//         false 인 숫자 count
    }
    
    reserve.sort((a,b)=>a-b);
    
    for(let x of reserve){
        if(x!==1 && !student[x-1]){
            student[x-1]=true;
            count--;
            continue;
        }
        if(x===n) continue;
        
        if(student[x+1]) continue;
        
        student[x+1]=true;
        count--;
        
    }
    
    answer=n-count;
    return answer;
}
profile
이전해요 ☘️ https://mei-zy.tistory.com

0개의 댓글