-
프로그래머스 풀이 : 호텔 대실알고리즘 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으로 관리하면 쉽게 풀 수 있다.
'알고리즘' 카테고리의 다른 글
섬 개수 세기 - dfs (1) 2024.10.19 백준 풀이 : 동전 1 - 2293번 (2) 2024.10.06 [99클럽 코테 스터디 2일차 TIL] JAVA 배열의 최대공약수(gcd), 최소공배수(lcm) 구하기 (4) 2024.07.23 dfs java (1) 2024.06.28 정렬 (1) 2024.04.04