前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode Container With Most Water

Leetcode Container With Most Water

作者头像
发布2018-09-04 11:37:02
4750
发布2018-09-04 11:37:02
举报
文章被收录于专栏:WD学习记录WD学习记录

题目:Container With Most Water

Given n non-negative integers a1a2, ..., an , where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

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.

Example:

代码语言:javascript
复制
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

解答:

第一想法两个for循环,但是很明显没有通过。

参考:[LeetCode]题解(python):011-Container With Most Water

代码语言:javascript
复制
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        size = len(height) # the size of height
        maxm = 0 # record the most water
        j = 0
        k = size - 1
        while j < k:
            if height[j] <= height[k]:
                maxm = max(maxm,height[j] * (k - j))
                j += 1
            else:
                maxm = max(maxm,height[k] * (k - j))
                k -= 1
        return maxm

效率更高的方法:sample 48 ms submission

代码语言:javascript
复制
class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """        
        i,j,max_v=0,len(height)-1,0
        while i<j:
            if height[i]<height[j]:
                short_p=height[i]
                v=short_p*(j-i)
                i+=1
                while i<j and height[i]<=short_p:
                    i+=1
            else:
                short_p=height[j]
                v=short_p*(j-i)
                j-=1
                while i<j and height[j]<=short_p:
                    j-=1
            if v>max_v:
                max_v=v
        return max_v
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年08月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:Container With Most Water
  • 解答:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档