[프로그래머스] 체육복 (java)

HaYeong Jang·2021년 3월 28일
0
post-thumbnail

🔗 문제링크

https://programmers.co.kr/learn/courses/30/lessons/42862

👩🏻‍💻 코드

import java.util.*;
import java.util.stream.IntStream;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        int answer = 0;
        boolean[] people = new boolean[n + 1];
        Arrays.fill(people, true);
        boolean[] able = new boolean[n + 1];

        for (int k : lost) {    // 잃어버린 사람
            people[k] = false;
        }
        for (int k : reserve) { // 빌려줄 수 있는 사람
            able[k] = true;
        }

        for (int i = 1; i <= n; i++) {  // 자신이 체육복을 잃어버린 경우
            int finalI = i;
            if (IntStream.of(lost).anyMatch(x -> x == finalI) && IntStream.of(reserve).anyMatch(x -> x == finalI)) {
                people[i] = true;
                able[i] = false;
            }
        }

        for (int k : reserve) { // 앞뒤로 빌려줄 수 있는 경우
            if (able[k] && !people[k - 1]) {	// 앞번호가 체육복이 없는 경우
                people[k - 1] = true;
            } else if (k + 1 <= n) {
                if (able[k] && !people[k + 1]) {	// 뒷번호가 체육복이 없는 경우
                    people[k + 1] = true;
                }
            }
        }

        for (int i = 1; i <= n; i++) {
            if (people[i]) {
                answer++;
            }
        }

        return answer;
    }
}

📝 정리

people: 체육수업을 들을 수 있는 사람
able: 체육복을 빌려줄 수 있는 사람

people과 able을 통해 여벌 체육복을 가져온 학생이 체육복을 빌려줄 수 있는지 판단하였고, 마지막에 people이 true인 사람을 세서 체육수업을 들을 수 있는 사람 수를 구했다.

profile
기억하기 위해 기록하는 개발로그👣

0개의 댓글