본문 바로가기
개발/알고리즘

[프로그래머스/JAVA] 체육복

by zuzuu 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
반응형

댓글