leetcode 11. Container With Most Water

因为一些事情已经有两天没刷leetcode了,从今天开始加油!一切都会慢慢变好的。

今日份leetcode 11. Container With Most Water
Description:
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.
leetcode 11. Container With Most Water
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

如图所示,题目的意思是找出两条直线使与x轴组成的容器装下的水最多,数组中的元素分别对应直线的高度。
注意:容器不能倾斜,数组元素最少是2个。

由于智商问题我是用暴搜做的

class Solution {
    public int maxArea(int[] height) {
        int max_Area = 0;
        for(int i=0;i<height.length-1;i++)
            for(int j=i+1;j<height.length;j++){
                if(height[i]>=height[j])
                    max_Area = Math.max(max_Area,height[j]*(j-i));
                else
                    max_Area = Math.max(max_Area,height[i]*(j-i));
            }
        return max_Area;
    }
}

复杂度太高O(n^2),当数据量变大时会很耗时。

下面的方法是利用双指针,分别指向数组的最左边元素和最右元素。因为最大容积取决于两条线的中低的一条线和两条线的距离。数组中各元素的大小情况不清楚,所以先从两条线的距离入手。逐渐缩小距离,来寻找最大的值。那么缩小距离是让左指针往右移动,还是右指针往左移动呢?应该是让指向高度较低的线的指针移动,如果是较高的线移动那肯定得到的值会变小(因为距离一定变小)。

class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
	    int maxArea = 0;

 	while (left < right) {
		maxArea = Math.max(maxArea, Math.min(height[left], height[right])* (right - left));
		if (height[left] < height[right])
			left++;
		else
			right--;
	 }
	return maxArea;
     }
}