Avoid Flood in The City LeetCode solution in Java

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

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0