LeetCode [11. Container With Most Water]

Problem

11. Container With Most Water

Question

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.

思路

直接暴力求解复杂度是O(n^2),如果给出数据太多肯定会超时。
仔细研究可以发现有以下规律,简化计算。
看以下例子:

假设有六段线段:1 2 3 4 5 6
用下面的形式简单表现一下两两线段组成的容器
从线段1 线段6开始双向遍历
   1 2 3 4 5 6
1            @
2  
3
4
5
6

存在两种情况

1. 线段6比1长或者相等
2. 线段6比1短
第一种情况下,线段1能组成的最大容器就是和线段6
第二种情况下,无法确定最大容器,但有一个规律,线段2、3、4、5就不需要和线段6结合去比较了,具体可看下面例子

1    2    3    4    5    6
|                   |
|    |    |         | 
|    |    |    |    |    |
|    |    |    |    |    |
--------------------------

**线段1和6**
1    2    3    4    5    6
|                    
|_________________________                     
|                        |
|                        |
--------------------------

**线段2和6**
1    2    3    4    5    6

     |____________________                     
     |                   |
     |                   |
--------------------------

很明显,既然线段6比较短,线段1和线段6组成的容器的宽度必然最大,后面的线段无论是长于6或者短于6,组成的容器必然没有线段1和线段6组成的大(装的水取决于最短的边)。
第一种情况下,已经找到线段1的最大容器,那么就让指向线段1的指针右移(不需要和线段2、3、4、5比较了),线段2和线段6比较,以此类推。
第二种情况下,指向线段6的指针左移,让线段1和线段5比较。按照以上规则继续进行即可。

(第一种情况)
   1 2 3 4 5 6
1  # # # # # @
2            @
3
4
5
6

(第二种情况)
   1 2 3 4 5 6
1          @ #
2            #
3            #
4            #
5            #
6            #

综上,代码思路就是,双向遍历,一个从头开始,一个从尾开始,按照以下规则:

  1. 左边的线段短,左边的位置右移
  2. 右边的线段短,右边的位置左移

Code

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0;
        int right = height.size()-1;
        int maxVolume = 0;
        while (left < right) {
            maxVolume = max(maxVolume, min(height[left], height[right])*(right-left));
            if (height[right] >= height[left]) {
                left++;
            }
            else {
                right--;
            }
        }
        return maxVolume;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值