zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):011-Container With Most Water

    题目来源:

    https://leetcode.com/problems/container-with-most-water/


    题意分析:

          给出一个n长度的非0数组,a1,a2,……,an,ai代表在坐标i上的高度为ai。以以ai,aj为高,i到j为底,可以构造出一个容器。那么求出这些容器中可以装的水的最大容积(容器不能倾斜)。例如数组[2,1],一共可以构造1个容器,这个容器的四个端点坐标是(0,0),(0,2),(1,1),(1,1),那么他可以装的最大的水容积是(1-0)*1 = 1.


    题目思路:

         我们不难发现,水容积的大小是由短高度决定的。暴力的方法就是把所有的容器找出来,算出他们的水容积,一一比较,然后得到最大值,这种方法的时间复杂度是(O(n^2))。很明显会TLE。

           我们认真研究一下寻找过程,我们从第一个高度为起始容器壁,那么我们直接以最后一个高度为终止壁,如果a1 <= an,那么以a1为起始的容器最大是a1 * (n - 1),以a1为容器壁的最大容器计算出来的。那么以a1为壁的所有情况不需要再考虑,接着考虑a2的;同理,如果a1 > an,an不再考虑,考虑an-1这有点类似"夹逼定理"。比较ai和aj(i<j)如果ai <= aj,i++;否者j ++直到i == j。这个算法的时间复杂度是(O(n))。


    代码(python):

     1 class Solution(object):
     2     def maxArea(self, height):
     3         """
     4         :type height: List[int]
     5         :rtype: int
     6         """
     7         size = len(height) # the size of height
     8         maxm = 0 # record the most water
     9         j = 0
    10         k = size - 1
    11         while j < k:
    12             if height[j] <= height[k]:
    13                 maxm = max(maxm,height[j] * (k - j))
    14                 j += 1
    15             else:
    16                 maxm = max(maxm,height[k] * (k - j))
    17                 k -= 1
    18         return maxm
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4817787.html

  • 相关阅读:
    1250. Check If It Is a Good Array
    380. Insert Delete GetRandom O(1)
    378. Kth Smallest Element in a Sorted Matrix
    341. Flatten Nested List Iterator
    387. First Unique Character in a String
    454. 4Sum II
    D
    勇敢的妞妞 ( 状压 + 思维)
    P1879 [USACO06NOV]玉米田Corn Fields (状压dp入门)
    G
  • 原文地址:https://www.cnblogs.com/chruny/p/4817787.html
Copyright © 2011-2022 走看看