题目

解法:贪心

总体思想是把0的位置储存下来。每当遇到已经满的湖泊,查看两个问题:1)是否能够干燥他 2)能干燥他的符合条件的最早位置
不能干燥有两种情况,一种是现在就没有保存好的0,第二种是,保存好的0出现在这个湖泊之前被下雨满的时间之前。
能干燥的情况,我们遵循贪心思想,找到最早的符合条件的干燥日。也就是之前湖泊下满之后出现的第一个0,这边用二分搜索找到这个位置。
bisect.bisect_right(array, index)返回array中从左往右第一个比index大的位置

class Solution:def avoidFlood(self, rains: List[int]) -> List[int]:# main idea: 1) if encounter a zero, we store it's index and append 1 2) if not zero, we will find the previous position of the rained lake, and try to see if we can find a day to dry this lake ahead of time. This day must be after the previous rain day of this laken = len(rains)# list of zero daysdry_days = []# dict storing the full lakes id and day id pairfull_lakes = {}ans = []for i in range(n):# if current day does not rain, add to dry list and answer append 1if rains[i] == 0:dry_days.append(i)ans.append(1)else:if rains[i] in full_lakes:# if encounter a rain to a lake but no dry day can use, return []if len(dry_days)==0:ans = []breakelse:# find the previous day when rain full this lakeindex = full_lakes[rains[i]]# find the first zero position after this index day, that is the earliest time we can dry this lakedry_pos=bisect.bisect_right(dry_days, index)# if no valid position found, return []if dry_pos>=len(dry_days):ans = []break# else, replace the prefilled 1 as the dried lake idelse:ans[dry_days[dry_pos]] = rains[i]dry_days.pop(dry_pos)# if the 'if' statement is not executed, means current rain is on a empty lake, so we add element to the full_lakes; Otherwise, we update the full lake id, they are all the same codefull_lakes[rains[i]] = i# no matter what happens, we will add -1 to the answerans.append(-1)return ans

二刷

总体思路:关键在于当碰到已经满了的湖再次下雨时如何处理。需要从逻辑和贪心两方面同时满足。从逻辑上讲,需要找到在这个湖上一次变满的后面的某天来清空这个湖。其次从贪心上讲找的这一天要尽量靠近
针对上面两个点,需要以下的关键操作:

  1. 首先需要一个map来储存lake:last_full_day的映射关系,这样当某个湖再次下雨时,我们就能快速找到之前变满的一天
  2. 其次需要知道变满的这一天后面第一个可以干燥的日子,所以用set+lower_bound结合。set是天然有序的,lower_bound用logn找到符合条件的那一天。其实用vector也可以,只是set删除一个元素的复杂度会比vector低。至于set erase的复杂度,感觉没有定论,不太说得清,但应该是比O(n)要低
class Solution {public:vector<int> avoidFlood(vector<int>& rains) {// saves the full lake as key and the day it gets fulled as valueunordered_map<int,int> full_lakes;// set to save the days that can dry lake in order. Have to choose set because it automatically saves the dry days in order// thus it will naturally be sortedset<int> dry_days;vector<int> ans;for(int i=0;i<rains.size();i++){if(rains[i] == 0){// if no rain today, we insert this day to dry days dry_days.insert(i);// but we don't know which lake to dry it, so put anylake here, it will get overwritten otherwise no hurt to dry some random lakeans.push_back(1);}else{int lake = rains[i];// if this lake is already fullif(full_lakes.count(lake)){// find the day when it became fullint full_day = full_lakes[lake];// try to find a day that can dry this lake after the day it gets full// greedy way, we dry it with the nearst dry_day// use upper_bound to find this nearest day// no difference of lower_boud or upper_bound here aince all vals are differentauto p = dry_days.upper_bound(full_day);// if we can't find such day, means we can't prevent the floodif(p == dry_days.end()) return {};int dry_day = *p;// erase by pointer is much faster because we don't need to find this element anymoredry_days.erase(p);ans[dry_day] = lake;}full_lakes[lake] = i;ans.push_back(-1);}}return ans;}
};

时间复杂度:O(nlogn),logn来源于二分搜索,如果set的erase操作也是低于logn的话
空间复杂度:O(n)

Leetcode 1488. Avoid Flood in The City(python)相关推荐

  1. LeetCode 1488. Avoid Flood in The City - Java - 优先队列

    题目链接:1488. 避免洪水泛滥 Your country has an infinite number of lakes. Initially, all the lakes are empty, ...

  2. 【LeetCode】91. Decode Ways 解题报告(Python)

    [LeetCode]91. Decode Ways 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fux ...

  3. 【Leetcode】 刷题之路1(python)

    leetcode 刷题之路1(python) 看到有大佬总结了一些相关题目,想着先刷一类. 1.两数之和 15.三数之和 16.最接近的三数之和 11.盛最多的水 18.四数之和 454.四数相加II ...

  4. LeetCode —— 面试题 08.12. 八皇后(Python)

    设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行.不同列,也不在对角线上.这里的"对角线"指的是所有的对角线,不只是平分整个棋盘的那两条对角线. ...

  5. Leetcode —— 1469. 寻找所有的独生节点(Python)

    二叉树中,如果一个节点是其父节点的唯一子节点,则称这样的节点为 "独生节点" .二叉树的根节点不会是独生节点,因为它没有父节点. 给定一棵二叉树的根节点 root ,返回树中 所有 ...

  6. 【LeetCode】935. Knight Dialer 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划TLE 空间换时间,利用对称性 优化空间复杂 ...

  7. 【Leetcode】刷题之路2(python)

    哈希映射类题目(简单题小试牛刀啦bhn) 242.有效的字母异位词 349.两个数组的交集 1002.查找常用字符 202.快乐数 383.赎金信 242. 有效的字母异位词 用python的Coun ...

  8. 【LeetCode】934. Shortest Bridge 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS + BFS 相似题目 参考资料 日期 题目地 ...

  9. 【LeetCode】127. Word Ladder 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/word-lad ...

最新文章

  1. 利用归并排序求逆序对
  2. 配置linux终端主题需要密码,Mac/Ubuntu下终端色彩主题设置
  3. CCF关于暂停NOIP竞赛的公告
  4. django的母板系统
  5. 漫画:什么是volatile关键字?(整合版)
  6. 从 活动选择问题 看动态规划和贪心算法的区别与联系
  7. sql如何遍历几百万的表_SQl SERVER 2000 遍历表中数据的方法
  8. linux之Ansible快速入门
  9. 智能家居通信协议科普,什么户型选择什么产品一文看懂
  10. 赛锐信息:5个方面帮您应对 SAP License 审计
  11. delphi 各新版本特性收集
  12. cisco 模拟器安装及交换机的基本配置实验心得_软考网络工程师级配置题总结 | 交换机配置、路由器配置、广域网接入配置、L2TP配置、IPSec配置、PIX防火墙配置...
  13. 排序:ORDER BY
  14. 情人节之Python版冰墩墩
  15. 分享一套永久免费的ChatGPT使用方法
  16. ActiveReportsJS3.0 详解 ActiveReportsJS3.X
  17. webstorm使用Prettier
  18. 计算机音乐谱 青花瓷,周杰伦经典曲目—钢琴谱:青花瓷(四音轨版)——五线谱.pdf...
  19. uniapp扫码功能兼容h5
  20. open、openat和close函数

热门文章

  1. 为什么要通过API接口来获取数据
  2. 在家赚钱的工作,这五种比较适合在家操作!
  3. 2023届秋招进入最卷阶段!
  4. VS Supercharger插件
  5. 歌谣学前端之react三个api之一续集
  6. 用WCAT进行IIS压力测试
  7. 产业互联网周报:钉钉被曝组织优化,涉及自研 SaaS、硬件部门;马斯克暂停Twitter收购;谷歌发布AlloyDB数据库服务...
  8. Oracle 19C搭建rac环境
  9. Holedox Moving POJ - 1324
  10. 什么软件可以听力打字测试,雅思听力1 - 在线打字测试(dazi.kukuw.com)