공부/알고리즘
프로그래머스 풀이 : 호텔 대실
확두뇌
2024. 10. 7. 16:10
import java.util.*;
//시간은 시각에 60 곱해서 다 분으로 관리하기!
//우선순위 큐
//큐에 비는 시간을 넣기
//큐에 몇개가 있느냐가 의도
class Solution {
public int solution(String[][] book_time) {
int answer = 1;
int[][] newList = new int[book_time.length][2];
Queue<Integer> queue = new PriorityQueue<Integer>();
//시간을 분으로 변환
for(int i=0; i<book_time.length; i++){
for(int j=0; j<2; j++){
newList[i][j] = Integer.parseInt(book_time[i][j].substring(0,2))*60+Integer.parseInt(book_time[i][j].substring(3,5));
}
}
//시작이 빠른 순으로 정렬
Arrays.sort(newList, new Comparator<int[]>(){
@Override
public int compare(int[] a, int[] b){
return a[0] - b[0];
}
});
queue.add(newList[0][1]+10);
for(int i=1; i < newList.length; i++){
if(queue.peek() <= newList[i][0]){
queue.poll();
queue.add(newList[i][1]+10);
}else{
answer++;
queue.add(newList[i][1]+10);
}
}
return answer;
}
}
시간과 분을 컴퓨터가 관리하려면 문자열이나 다른 방식으로 하면 힘들다.
이때는 최소 단위로 바꿔서 관리하자!
예를들어 09:10은 9*60+10 = 550로 저장해서 관리하자.
또 이 문제의 핵심은 두가지다.
1. 시작 시간을 기준으로 정렬하고
2. 우선순위큐를 사용해서 사용 가능한 시간을 넣어 minheap으로 관리하면 쉽게 풀 수 있다.