活跃农民
- 积分
- 398
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-8-8
- 最后登录
- 1970-1-1
|
明天面试,多谢楼主面经,写了一份看起来还算简单的代码,用两个优先队列。一个用来存正在进行的meeting和这个meeting使用的roomId,一个用来存可用的room。每次新来一个meeting的时候,把结束的meeting释放出来,并且把room也释放。
- import java.util.*;
- class Untitled {
- public static void getAllRooms(int[][] rooms) {
- if (rooms == null || rooms.length == 0) {
- return;
- }
- Arrays.sort(rooms, new Comparator<int[]>(){
- public int compare(int[] a, int[] b) {
- if (a[0] == b[0]) {
- return a[1] - b[1];
- } else {
- return a[0] - b[0];
- }
- }
- });
-
- PriorityQueue<int[]> running = new PriorityQueue<>(10, new Comparator<int[]>() {
- public int compare(int[] a, int[] b) {
- if (a[0] == b[0]) {
- return a[1] - b[1];
- } else {
- return a[0] - b[0];
- }
- }
- });
- PriorityQueue<Integer> emptyRoom = new PriorityQueue<>();
- List<List<int[]>> result = new ArrayList<>();
- for (int i = 0; i < rooms.length; i++) {
- int[] current = rooms[i];
- // pop finished meeting first
- while(running.size() != 0 && current[0] >= running.peek()[0]) {
- int[] run = running.remove();
- emptyRoom.add(run[1]);
- }
- // get the room id
- int id = 0;
- if (emptyRoom.size() != 0) {
- id = emptyRoom.remove();
- } else {
- id = result.size();
- result.add(new ArrayList<>());
- }
- // add current to room
- result.get(id).add(current);
- // run meeting
- running.add(new int[]{current[1], id});
- }
- for (int i = 0; i < result.size(); i++) {
- System.out.print("Room " + (i + 1) + ": ");
- for (int[] meeting : result.get(i)) {
- System.out.print("[" + meeting[0] + "," + meeting[1] + "],");
- }
- System.out.println("");
- }
- }
- public static void main(String[] args) {
- getAllRooms(new int[][]{{3,6}, {6,9}, {5,7}});
- }
- }
复制代码 |
|