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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| public class ClosestRoom { public int[] closestRoom(int[][] rooms, int[][] queries) { return main(rooms , que); }
static class C1 { private int size; private int id; private int type; private int querieIndex; public C1(int type, int id, int size) { this.type = type; this.id = id; this.size = size; } public int getSize() { return this.size; } public boolean isQuerie() { return this.type == 1 ? true : false; } public int getId() { return this.id; } public void setQuerieIndex(int index) { this.querieIndex = index; } public Integer getQuerieIndex() { return this.querieIndex; } } public static int[] main(int[][] rooms, int[][] queries) { int[] result = new int[queries.length]; List<C1> c1List = new ArrayList<>(); for (int[] room : rooms) { C1 c1 = new C1(0, room[0], room[1]); c1List.add(c1); } int index = 0; for (int[] querie : queries) { C1 c1 = new C1(1, querie[0], querie[1]); c1.setQuerieIndex(index); index++; c1List.add(c1); } Collections.sort(c1List, new Comparator<C1>() { @Override public int compare(C1 o1, C1 o2) { return Integer.compare(o2.getSize(), o1.getSize()); } }); TreeSet<Integer> roomIdTree = new TreeSet<>(); for (C1 c1 : c1List) { if (!c1.isQuerie()) { roomIdTree.add(c1.getId()); continue; } result[c1.getQuerieIndex()] = getMinRoomId(roomIdTree, c1); } return result; } public static int getMinRoomId(TreeSet<Integer> roomIdTree, C1 c1) { if (roomIdTree.isEmpty()) { return -1; } Integer ceiling = roomIdTree.ceiling(c1.getId()); Integer floor = roomIdTree.floor(c1.getId()); if (ceiling == null){ return floor; }else if (floor == null){ return ceiling; }else{ return Math.abs(ceiling - c1.getId()) >= Math.abs(floor - c1.getId()) ? floor : ceiling; } } }
|