def fast_sort(nums):
start = 0
end = len(nums) - 1
def _fast_sort(ll, s, e):
if s >= e:
return
left = s
right = e
pivot = ll[left]
while left <= right:
while left <= right and ll[left] <= pivot:
left += 1
while left <= right and ll[right] >= pivot:
right -= 1
if left <= right:
ll[left], ll[right] = ll[right], ll[left]
ll[s], ll[right] = ll[right], ll[s]
_fast_sort(ll, s, right-1)
_fast_sort(ll, right + 1, e)
_fast_sort(nums, start, end)
return nums
if __name__ == '__main__':
a = [234, 34, 53464567, 57, 65, 234, 23, 2, 3, 3, 543, 3, 345, 542, 5, 4676, 56, 75, 76, 23, 23, 434, 6, 456, 5]
print(fast_sort(a))
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
个人解答:
class Solution:
def trap(self, height: List[int]) -> int:
if len(height) <= 2:
return 0
start = 0
end = len(height) -1
l_max = height[start]
r_max = height[end]
all_sum = l_max + r_max
# 双指针分别扫过左右最大值组成的面积
while start < end:
ret = 0
if l_max > r_max:
end -= 1
ret = r_max = max(r_max, height[end])
else:
start += 1
ret = l_max = max(l_max, height[start])
if start < end:
all_sum += ret
# 用所有的面积减去本身的面积就是雨水的面积
return all_sum - sum(height)