LeetCode 笔记八 2019/10/2
Container With Most Water
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Example
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
简单点说就是把纵坐标比作水池的高,横坐标是水池的宽,看水池最多能存多少水。
Code
一开始是这么写的:
import numpy as np
class Solution:
def maxArea(self, height: List[int]) -> int:
index = [i for i in range(len(height))]
index = np.array(index)
area = 0
for i in range(len(height)):
temp = [min(h, height[i]) for h in height]
temp = np.array(temp) * (index - i)
area = max(area, max(temp))
return area
其实我觉得这个也没错,但在第43个test报了时间超出的错误:
Status: Time Limit Exceeded
本来想转战两次遍历,但想了下好像跟这个一样。后来又改了下,从两头往中间逼近:
import numpy as np
class Solution:
def maxArea(self, height: List[int]) -> int:
area = 0
i = 0
j = len(height) - 1
while i != j:
if height[i] < height[j]:
area = max(area, height[i] * (j - i))
i += 1
else:
area = max(area, height[j] * (j - i))
j -= 1
return area
结果:
50 / 50 test cases passed.
Runtime: 180 ms
Memory Usage: 29.2 MB
Runtime: 180ms, faster than 5.98% of Python3 online submissions for Container With Most Water.
Memory Usage: 29.2MB, less than 5.26% of Python3 online submissions for Container With Most Water.
我一直在想是不是要改用c写呢?但想了下,似乎Python更符合现在我的需求。所以决定先过一遍Python再说啦!