Leetcode11 Container With Most Water 解题思路 (Python)

时间:2023-03-08 22:59:06
Leetcode11 Container With Most Water 解题思路 (Python)

今天开始第一天记录刷题,本人编程小白,如果有写的不对、或者能更完善的地方请个位批评指正!

准备按tag刷,第一个tag是array:

这个是array的第一道题:11. 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.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

 (From: https://leetcode.com/problems/container-with-most-water/description/)

思路:

  这道题是找:(取两个数组元素中比较小的哪个数字)*两数组元素之间宽度(i.e.,|最大数字的数组下标-最小数字的数字下标+1|)的最大值

  除了可以用嵌套for循环之外(时间复杂度O(n^2)),我的想法是:

    第一步:先用数组中的第一个元素和最后一个元素来计算,因为这个时候的宽度是最宽的

    第二至第n步:然后取第一个和最后一个数字中相对大一点的数字,依次向中间渐进。

    结束条件:第一个数向后渐进的数组下标等于最后一个数向前渐进的数组的下标。

  这样的话可以实现复杂度:O(n)

Python 代码实现:

class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
front_index = 0
end_index = len(height) - 1
water = (len(height)-2)*min(height[len(height)-1],height[0])
while(front_index != end_index):
water_temp = (end_index - front_index)*min(height[front_index],height[end_index])
if height[front_index] > height[end_index]:
end_index -= 1
if water_temp >= water:
water = water_temp
elif height[front_index] <= height[end_index]:
front_index += 1
if water_temp >= water:
water = water_temp
return water
height = [1,8,6,2,5,4,8,3,7]
print(maxArea(0,height))