Avoid Flood in The City LeetCode solution in Java
1class Solution {2public int[] avoidFlood(int[] rains) {3// the previous appeared idx of rains[i]4Map<Integer, Integer> map = new HashMap<>();5TreeSet<Integer> zeros = new TreeSet<>();6int[] res = new int[rains.length];7for (int i = 0; i < rains.length; i++) {8if (rains[i] == 0) {9zeros.add(i);10} else {11if (map.containsKey(rains[i])) {12// find the location of zero that can be used to empty rains[i]13Integer next = zeros.ceiling(map.get(rains[i]));14if (next == null) return new int[0];15res[next] = rains[i];16zeros.remove(next);17}18res[i] = -1;19map.put(rains[i], i);20}21}22for (int i : zeros) res[i] = 1;23return res;24}25}