๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/JAVA] ์ฒด์œก๋ณต

by ynzu๐Ÿค 2022. 7. 25.
๋ฐ˜์‘ํ˜•


๐Ÿ‘‡ ๋ฌธ์ œ URL ๐Ÿ‘‡

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr


ํƒ์š•๋ฒ• ๋ฌธ์ œ!
ํƒ์š•๋ฒ•์ด๋ž€ ๋งค ์„ ํƒ์—์„œ ์ตœ์ ์˜ ๊ฒฐ๊ณผ๋ฅผ ๋งŒ๋“ค์–ด๋‚ด๋Š” ๊ฒƒ.

์ถœ์ฒ˜ :https://gomguard.tistory.com/119

import java.util.Arrays;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer = n;
        int[] student = new int[n];

        //์ผ๋‹จ ๋ชจ๋‘ ์ฒด์œก๋ณต์„ ๊ฐ€์ ธ์˜จ ๊ฒƒ์œผ๋กœ ์„ธํŒ… (1,1,1,1,1)
        Arrays.fill(student, 1);
        Arrays.sort(lost);
        Arrays.sort(reserve);
        
        //์žƒ์–ด๋ฒ„๋ฆฐ ํ•™์ƒ์€ -1 ์ฒ˜๋ฆฌ (1,0,1,0,1)
        for (int i : lost) {
            student[i - 1] -= 1;
        }

        //์—ฌ๋ฒŒ์„ ๊ฐ€์ ธ์˜จ ํ•™์ƒ์€ +1 ์ฒ˜๋ฆฌ (2,0,2,0,2)
        for (int i : reserve) {
            student[i - 1] += 1;
        }

        for (int i = 0; i < student.length; i++) {
            if (student[i] == 0) {
                
                //์ฒซ๋ฒˆ์งธ์ผ ๋•Œ๋Š” ์˜ค๋ฅธ์ชฝ๋งŒ ๊ฒ€์‚ฌ
                if(i==0){
                    if(student[i+1] == 2){
                        student[i+1] -= 1;
                        student[i] = 1;
                    }

                //๋งˆ์ง€๋ง‰์ผ ๋•Œ๋Š” ์™ผ์ชฝ๋งŒ ๊ฒ€์‚ฌ
                }else if(i==n-1){
                    if(student[i-1] == 2){
                        student[i-1] -= 1;
                        student[i] = 1;
                    }
                }else{
                    //์–‘์ชฝ ๋‹ค ๊ฒ€์‚ฌ, ๋จผ์ € ์ž์‹ ์˜ ์™ผ์ชฝ๋ถ€ํ„ฐ ๊ฒ€์‚ฌ
                    if(student[i-1] == 2){
                        student[i-1] -= 1;
                        student[i] = 1;
                    }
                    else if(student[i+1] == 2){
                        student[i+1] -= 1;
                        student[i] = 1;

                    }

                }


            }
        }

      
        for(int s : student){
            if( s == 0){
                answer -= 1;
            }
        }
        return answer;
    }
}

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€