Notice
Recent Posts
Recent Comments
Link
«   2026/05   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

yesolje

프로그래머스_고득점kit_그리디_체육복 본문

코딩테스트

프로그래머스_고득점kit_그리디_체육복

yesolje 2025. 3. 11. 11:17

풀이

import java.util.HashSet;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        // 1. Set을 사용해 중복 제거
        HashSet<Integer> lostSet = new HashSet<>();
        HashSet<Integer> reserveSet = new HashSet<>();

        for (int l : lost) {
            lostSet.add(l);
        }
        for (int r : reserve) {
            // 여벌이 있지만 도난당한 경우 먼저 처리
            if (lostSet.contains(r)) {
                lostSet.remove(r);
            } else {
                reserveSet.add(r);
            }
        }

        // 2. 체육복 빌려주기
        for (int r : reserveSet) {
            if (lostSet.contains(r - 1)) { // 앞번호 학생에게 빌려주기
                lostSet.remove(r - 1);
            } else if (lostSet.contains(r + 1)) { // 뒷번호 학생에게 빌려주기
                lostSet.remove(r + 1);
            }
        }

        // 3. 최종적으로 체육복을 가진 학생 수 반환
        return n - lostSet.size();
    }
}