LeetCode-6:接雨水
Posted il_持之以恒_li
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-6:接雨水相关的知识,希望对你有一定的参考价值。
原题为:
参考代码为:
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
n = len(height)
dp = [0] * n
left = 0
right = n - 1
max_v = height[0]
max_index = 0
for i in range(n):
if height[i] > max_v:
max_v = height[i]
max_index = i
for i in range(0, max_index + 1):
if height[i] > height[left]:
left = i
dp[i] = height[i]
else:
dp[i] = height[left]
for i in range(n - 1, max_index, -1):
if height[i] > height[right]:
right = i
dp[i] = height[i]
else:
dp[i] = height[right]
sum_1 = 0
for i in range(n):
sum_1 += dp[i] - height[i]
return sum_1
个人思路如下:
拿上图举个例子吧!如果我们把上图柱子的高度和(图二)减去原来柱子的高度和(图一)是不是就是所要求的结果了呀!那么怎样才能得到图二的数据呢?小编觉得这样,先遍历原来列表,找到列表中柱子最高的下标索引max_index,之后,再重新遍历列表。
当下标索引小于等于max_index的情况下,
如果(left初始值为0)height[left]<height[i],那么,left = i,dp[i] = height[i];
否则,dp[i] = height[left],(这里dp是一个列表,长度为height的长度,初始值为[0]*height的长度)下标索引大于max_index的情况和上述判断差不多。
执行效率:
改进:
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
n = len(height)
left = 0
right = n - 1
max_v = height[0]
max_index = 0
for i in range(n):
if height[i] > max_v:
max_v = height[i]
max_index = i
sum_1 = 0
for i in range(0,n):
if i <= max_index:
if height[i] > height[left]:
left = i
dp = height[i]
else:
dp = height[left]
sum_1 += dp - height[i]
else:
right_index = n-(i-max_index)
if height[right_index] > height[right]:
right = right_index
dp = height[right_index]
else:
dp = height[right]
sum_1 += dp - height[right_index]
return sum_1
执行效率:
以上是关于LeetCode-6:接雨水的主要内容,如果未能解决你的问题,请参考以下文章