LeetCode 11. Container With Most Water (装最多水的容器)

本文介绍了一种解决LeetCode上“最大盛水容器”问题的有效算法。该问题要求找出两条线段,使得它们与x轴形成的容器能盛最多的水。文章详细解释了使用双指针法从两端逼近寻找最优解的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 


题目标签:Array

  这道题目给了我们一个height array, 每一个数字代表一条竖直线的高度,从x轴开始。一开始用暴力法没通过。所以要用特别方法来做。分析一下,如何才能够拿到更多的水。如果一根线很低,另外一根很高,那么水只能装到低的那根线,等于把高出的区域浪费了。那么需要找到更高的线来替代低的那条才有希望找到装水更多的两条线。设两个pointer,left 和 right。 从最两边开始遍历,每一次都计算面积,比max大的话就替换。接着把低的那根线的pointer 向另外一边移动,直到两个pointers 相遇。

 

Java Solution:

Runtime beats 31.31% 

完成日期:07/11/2017

关键词:Array

关键点:Two Pointers

 

 1 public class Solution 
 2 {
 3     public int maxArea(int[] height) 
 4     {
 5         int left = 0;
 6         int right = height.length-1;
 7         int max_area = -1;
 8         
 9         while(left < right)
10         {
11             int len = right - left;
12             int ht = Math.min(height[left], height[right]);
13             max_area = Math.max(max_area, len*ht);
14             
15             if(height[left] < height[right])
16                 left++;
17             else
18                 right--;
19             
20         }
21         
22         return max_area;
23     }
24 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

转载于:https://www.cnblogs.com/jimmycheng/p/7152719.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值