蜗牛慢慢爬 LeetCode 11. Container With Most Water [Difficulty: Medium]

时间:2022-12-29 14:16:12

题目

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.

翻译

给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。绘制n条垂直线,使得线i的两个端点处于(i,ai)和(i,0)。找到两条线,它们与x轴一起形成容器,使得容器含有最多的水。

Hints

Related Topics: Array, Two Points
容器是有木桶效应的 也就是说短的垂直线决定了整个容器的高 所要求的是 max(短边*坐标差)
找到一些最大值的一般想法是通过可能发生最大值的所有情况,并继续更新最大值。为了提高扫描效率,要找到一种智能的扫描方式来切断无用的情况,同时100%保证通过其他情况可以达到最大值
这儿可以通过设置左右两端的初始指针,向中间扫描,每次只移动较小值的指针 每一次移动都更新最大值

代码

Java

class Solution {
public int maxArea(int[] height) {
int left,right;
left = 0;right = height.length-1;
int maxArea = 0;
while(left<right){
maxArea = Math.max(maxArea, (right-left)*(Math.min(height[left],height[right])));
if(height[left]<height[right])
left++;
else
right--;
}
return maxArea;
}
}

Python

class Solution(object):
def maxArea(self, height):
l = 0; r = len(height)-1;
maxArea = 0
while l<r:
maxArea = max(maxArea, (r-l)*min(height[l],height[r]))
if height[l]<height[r]:
l += 1
else:
r -= 1
return maxArea