forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAvoid flood in city
31 lines (28 loc) · 875 Bytes
/
Avoid flood in city
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
import collections
import heapq
class Solution(object):
def avoidFlood(self, rains):
"""
:type rains: List[int]
:rtype: List[int]
"""
lookup = collections.defaultdict(list)
i = len(rains)-1
for lake in reversed(rains):
lookup[lake].append(i)
i -= 1
result, min_heap = [], []
for i, lake in enumerate(rains):
if lake:
if len(lookup[lake]) >= 2:
lookup[lake].pop()
heapq.heappush(min_heap, lookup[lake][-1])
result.append(-1)
elif min_heap:
j = heapq.heappop(min_heap)
if j < i:
return []
result.append(rains[j])
else:
result.append(1)
return result if not min_heap else []