LC.P1488[避免洪水泛滥] 方法一:贪心+哈希表+有序集合12345678910111213141516171819202122232425class 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)$