구명보트
문제정의
최대 2명까지 탈 수 있고 무게 제한이 limit인 구명보트를 최대한 적게 사용해서 사람들을 보트에 태우는 문제이다.
문제풀이
전체 코드는 다음과 같다. 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47package level2;
import java.util.Collections;
import java.util.PriorityQueue;
public class LifeBoat {
    //프로그래머스 문제풀이 level2 구명보트
    public static void main(String[] args) {
        int[] people = {70, 50, 80, 50};
        int limit = 100;
        int answer = 0;
        PriorityQueue<Integer> small = new PriorityQueue<>();
        PriorityQueue<Integer> big = new PriorityQueue<>(Collections.reverseOrder());
        for(int w : people)
        {
            if(w <= limit/2)
                small.add(w);
            else
                big.add(w);
        }
        while((!small.isEmpty()) && (!big.isEmpty()))
        {
            int s = small.peek();
            int b = big.peek();
            if(s+b > limit)
            {
                big.remove();
                answer++;
            }
            else
            {
                small.remove();
                big.remove();
                answer++;
            }
        }
        if(!small.isEmpty())
            answer += small.size() % 2 == 0 ? small.size()/2 : small.size()/2+1;
        else
            answer += big.size();
        System.out.println(answer);
    }
    
}
우선 순위 큐를 활용했으므로 총 시간복잡도는 \(O(nlogn)\)이 된다.
테스트
처음에 40번째 줄에 else가 아니라 else if문을 썼는데 효율성 테스트를 하나 통과하지 못했다. 그래서 else로 바꾸니 통과가 되었다. size를 한번 더 호출하냐 마냐가 차이인 것 같은데, 효율성 테스트가 조금 빡빡하단 생각이 들었다.