LeetCode 笔记八 水池储水问题

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
example

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再说啦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值