码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-1488-避免洪水泛滥

时间:2020-06-26 11:00:34      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:==   collect   heapq   cti   lazy   enumerate   res   二分   src   

题目描述:

技术图片

 

 技术图片

 

 技术图片

 

 提交:

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

 

leetcode-1488-避免洪水泛滥

标签:==   collect   heapq   cti   lazy   enumerate   res   二分   src   

原文地址:https://www.cnblogs.com/oldby/p/13193900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!