2-SUM 同类型题目, 与LeetCode11思想相似
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcosfor contributing this image!
- 这题会卡时间限制,要求使用O(n)的方法来解决这个问题;
- 实际上只需要计算每个格子左右的高度最大值中取较小的那个与当前的高度取正差值即可;
- 优化:可以仅遍历一次就完成计算,即设置左指针与右指针,并且记录左指针左边的最大值以及右指针右边的最大值,每次比较两个最大值,如果左最大值小于右最大值,那么右边不会对左指针指的位置产生限制,直接用左最大值计算即可,右边同理;
Python Code
1 | class Solution: |