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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| class Solution { public int robotSim(int[] commands, int[][] obstacles) { int result = 0; int direction = 400; int[] reboot = new int[2];
HashMap<Integer, List<Integer>> xHashMap = new HashMap<>(); HashMap<Integer, List<Integer>> yHashMap = new HashMap<>();
for (int[] obstacle : obstacles) { if (xHashMap.containsKey(obstacle[0])) { List<Integer> list = xHashMap.get(obstacle[0]); list.add(obstacle[1]); xHashMap.replace(obstacle[0], list); } else { List<Integer> list = new ArrayList<>(); list.add(obstacle[1]); xHashMap.put(obstacle[0], list); } if (yHashMap.containsKey(obstacle[1])) { List<Integer> list = yHashMap.get(obstacle[1]); list.add(obstacle[0]); yHashMap.replace(obstacle[1], list); } else { List<Integer> list = new ArrayList<>(); list.add(obstacle[0]); yHashMap.put(obstacle[1], list); } }
for (Map.Entry<Integer, List<Integer>> tem : xHashMap.entrySet()) { tem.getValue().sort(((o1, o2) -> (o1 - o2))); } for (Map.Entry<Integer, List<Integer>> tem : yHashMap.entrySet()) { tem.getValue().sort(((o1, o2) -> (o1 - o2))); }
for (int command : commands) { if (command < 0) { direction = command == -1 ? direction + 1 : direction - 1; } else { int temp = direction % 4; switch (direction % 4) { case 0 : if (xHashMap.containsKey(reboot[0])) { reboot[1] = selectIndex(reboot[1], command, xHashMap.get(reboot[0])); } else { reboot[1] += command; } break; case 1 : if (yHashMap.containsKey(reboot[1])) { reboot[0] = selectIndex(reboot[0], command, yHashMap.get(reboot[1])); } else { reboot[0] += command; } break; case 2 : if (xHashMap.containsKey(reboot[0])) { reboot[1] = selectIndex(reboot[1], -1 * command, xHashMap.get(reboot[0])); } else { reboot[1] -= command; } break; case 3 : if (yHashMap.containsKey(reboot[1])) { reboot[0] = selectIndex(reboot[0], -1 * command, yHashMap.get(reboot[1])); } else { reboot[0] -= command; } break; }
if ((reboot[0] * reboot[0] + reboot[1] * reboot[1]) > result) { result = reboot[0] * reboot[0] + reboot[1] * reboot[1]; } } } return result; }
private static int selectIndex(int index, int l, List<Integer> list) { if (l > 0) { if (index >= list.get(list.size() - 1) || (index + l) < list.get(0)) { return index + l; }
int i = 0; for (; index > list.get(i); i++) { }
if (index + l > list.get(i)) { return list.get(i) - 1; } return index + l; } else { if (index <= list.get(0) || (index + l) > list.get(list.size() - 1)) { return index + l; }
int i = list.size() - 1; for (; index < list.get(i); i--) { }
if (index + l < list.get(i)) { return list.get(i) + 1; } return index + l; } } }
|