直方图水量
1、两边收缩~ 好!!!
从两边收缩,因为本来就是通过两边来的,所以两边的最值是可以肯定的。如果左边的最值比右边的最值小,那么左边的水量是可以肯定的,肯定是短板~
class Solution:
def trap(self, height: List[int]) -> int:
result = 0
left = 0
right = len(height) - 1
left_max = 0
right_max = 0
while left <= right:
if left_max <= right_max: # left是短板
left_max = max(left_max, height[left])
result += left_max - height[left]
left += 1
else: # right是短板
right_max = max(height[right], right_max)
result += right_max - height[right]
right -= 1
return result
2、自己的解法
就是一次计算每一个点的左边最值和右边最值,但是会做记录,相当于剪枝。不过还是没有很好的利用好左边和右边比较好的最值。第一种方法最好~~
class Solution:
def trap(self, nums: List[int]) -> int:
# 思路就是每一个位置的左边最大和右边最大,取min。
n = len(nums)
result = 0
res1 = 0
res2 = 0
for i in range(1, n-1):
if res2 < i:
res2 = i + 1
tmp = res2
for j in range(tmp, n):
if nums[j] > nums[res2]:
res2 = j
if min(nums[res1], nums[res2]) > nums[i]:
result += min(nums[res1], nums[res2]) - nums[i]
if nums[i] >= nums[res1]:
res1 = i
return result
3、求出每个柱子的左边的最值和右边的最值。
时间复杂度:预处理出两个最大值数组,复杂度为 O(n)O(n);计算每根柱子可接的雨水量,复杂度为 O(n)O(n)。整体复杂度为 O(n)O(n)。空间复杂度:使用了数组存储两侧最大值。复杂度为 O(n)O(n)。