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
| class Solution { public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) { int n = positions.length; Map<Integer, Integer> posToIdx = new HashMap<>(), posToHealth = new HashMap<>(); Map<Integer, Character> posToDir = new HashMap<>(); for (int i = 0; i < n; ++i) { posToIdx.put(positions[i], i); posToHealth.put(positions[i], healths[i]); posToDir.put(positions[i], directions.charAt(i)); } Arrays.sort(positions); Stack<Integer> stack = new Stack<>(); for (int i = 0; i < n; ++i) { boolean alive = true; char dir = posToDir.get(positions[i]); while (alive && !stack.isEmpty() && dir == 'L' && posToDir.get(stack.peek()) == 'R' ) { int topPos = stack.peek(); int topHealth = posToHealth.get(topPos); if (posToHealth.get(positions[i]) > topHealth) { stack.pop(); posToHealth.put(positions[i], posToHealth.get(positions[i]) - 1); } else if (posToHealth.get(positions[i]) < topHealth) { alive = false; posToHealth.put(topPos, posToHealth.get(topPos) - 1); } else { alive = false; stack.pop(); } } if (alive) stack.push(positions[i]); } int[] newHealths = new int[n]; while (!stack.isEmpty()) { int pos = stack.pop(); int index = posToIdx.get(pos), health = posToHealth.get(pos); newHealths[index] = health; } List<Integer> survivor = new LinkedList<>(); for (int x : newHealths) if (x != 0) survivor.add(x); return survivor; } }
|