[프로그래머스/Greedy] Level 1 체육복 (JAVA)

Jiwoo Kim·2021년 3월 26일
0

알고리즘 정복하기

목록 보기
33/85
post-thumbnail

문제


풀이


코드

import java.util.*;
import java.util.stream.Collectors;

class Solution {
    
    private Set<Integer> losts = new HashSet<>();
    private Set<Integer> reserves = new HashSet<>();

    public int solution(int n, int[] lost, int[] reserve) {
        losts.addAll(Arrays.stream(lost).boxed().collect(Collectors.toList()));
        reserves.addAll(Arrays.stream(reserve).boxed().collect(Collectors.toList()));
        int reserveButLost = countReserveButLost();
        int borrowSuccess = countBorrowSuccess();
        return n - (lost.length - reserveButLost) + borrowSuccess;
    }


    private int countReserveButLost() {
        Set<Integer> reserveButLosts = new HashSet<>();
        for (int reserveStudent : reserves)
            for (int lostStudent : losts)
                if (reserveStudent == lostStudent)
                    reserveButLosts.add(reserveStudent);
        reserves.removeAll(reserveButLosts);
        losts.removeAll(reserveButLosts);
        return reserveButLosts.size();
    }

    private int countBorrowSuccess() {
        int count = 0;
        for (int lostStudent : losts)
            if (reserves.remove(lostStudent - 1) || reserves.remove(lostStudent + 1))
                count++;
        return count;
    }
}

0개의 댓글