LC.P1488[避免洪水泛滥]

方法一:贪心+哈希表+有序集合

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
class Solution {
public int[] avoidFlood(int[] rains) {
int n = rains.length;
int[] ans = new int[n];
Arrays.fill(ans, -1);
TreeSet<Integer> sunny = new TreeSet<>();
Map<Integer, Integer> rainy = new HashMap<>();
for (int i = 0; i < n; ++i) {
int k = rains[i];
if (k > 0) {
if (rainy.containsKey(k)) {
Integer t = sunny.higher(rainy.get(k));
if (t == null) return new int[0];
ans[t] = k;
sunny.remove(t);
}
rainy.put(k, i);
} else {
sunny.add(i);
ans[i] = 1;
}
}
return ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$