[LeetCode] Container With Most Water

Well, an interesting problem. If you draw some examples on a white board and try to figure out the regularities, you may have noticed that the key to solving this problem is to use two pointers, one starting from the left end and the other starting from the right end. We compute an area for one configuration of the two pointers. Then we need to move them. If the left pointer has lower height, then we know it must be moved to one point with larger height in the right to make it possible for the area to increase. For the right pointer, the case is similar.

The following code is not well optimized, but being pretty short :-)

复制代码
 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         int l = 0, r = height.size() - 1, area = 0;
 5         while(l < r) {
 6             area = max(area, min(height[r], height[l]) * (r - l));  
 7             height[l] <= height[r] ? l++ : r--;
 8         }
 9         return area;
10     }
11 };
复制代码

You may avoid unnecessary checks by moving the left and right pointers to another place with larger height. However, the following code runs slower than the above one...

复制代码
 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         int l = 0, r = height.size() - 1, area = 0;
 5         while(l < r) {
 6             int h = min(height[l], height[r]), w = r - l;
 7             area = max(area, h * w);  
 8             while (height[l] <= h && l < r) l++;
 9             while (height[r] <= h && r > l) r--;
10         }
11         return area;
12     }
13 };
复制代码

Since the problem is not that hard, you may be required to think more, such at its time complexity. Could you prove that it runs in O(n) time? Well, this link has a very clever proof.

posted @   jianchao-li  阅读(234)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
点击右上角即可分享
微信分享提示