LeetCode [11. Container With Most Water]

来源:互联网 发布:java接口对于耦合实例 编辑:程序博客网 时间:2024/06/05 14:55

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 61            @2  3456存在两种情况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 61  # # # # # @2            @3456(第二种情况)   1 2 3 4 5 61          @ #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;    }};