题目描述:
提交:
class Solution: from typing import List def avoidFlood(self, rains: List[int]) -> List[int]: import heapq heap = [] res = [-1 if i != 0 else i for i in rains] import collections dic = collections.defaultdict(list) for i in range(len(rains)): dic[rains[i]].append(i) if rains[i] != 0 and len(dic[rains[i]]) > 1: heapq.heappush(heap,(dic[rains[i]][-1],dic[rains[i]][-2],rains[i])) tmp = dic[0] # print(tmp) i = 0 if len(tmp) < len(heap): return [] for n in heap: i = 0 while(i < len(tmp)): # print(n) if n[0] > tmp[i] > n[1]: res[tmp[i]] = n[2] tmp.pop(i) break elif i == len(tmp) -1 or n[0] < tmp[i]: return [] i += 1 res=[1 if i == 0 else i for i in res] return res
方法二:贪心 + 二分
class Solution: def avoidFlood(self, rains: List[int]) -> List[int]: def search(start, end, norain): # print(norain) i = 0 j = len(norain)-1 while i<=j: media = (i+j)//2 if norain[media] < start: i = media+1 elif norain[media]>end: j = media-1 else: re = norain[media] del(norain[media]) return re, True return 0, False re = [-1]*len(rains) norain = [] lake_day = {} for i, rain in enumerate(rains): if rain == 0: re[i] = 1 norain.append(i) else: if rain not in lake_day: lake_day[rain] = i else: start = lake_day[rain] end = i ind, test = search(start, end, norain) if not test: return [] lake_day[rain]=i re[ind] = rain return re