LeetCode Container With Most Water (Two Pointers)

题意

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.


就是说在x轴上有一堆竖线,要选出两根来,让它们形成的容器能装最多的水。

解法

看到Tag里的提示是Two Pointers,这个标签在CF里也经常看到,以前不知道是什么意思,这次学了一下,就是用两个指针来找解的办法,比如在排好序的数组里找出两个数让他们的和等于某个值,就可以在数组左右两端各放一个指针,如果他们指向的值的和大于要求的值就向左移动右指针使值变小,反之就向右移动左指针使值变大。

这里有一篇优秀的教程。

在这题里,同样在数组的左右两边设置两个指针,这时候容器的宽是最大的,任何移动都会使宽变小,所以如果要将容积增大,唯一的做法就是增加高,所以如果某个点的值小于指针指向的两个值中最小的那个,那么就可以略过。

class	Solution
{
public:
    int	maxArea(vector<int>& height)
    {
	    int	len = height.size();
	    int	l = 0,r = len - 1;
	    int	temp = 0,ans = 0;
	    int	min_height = 0;

	    while(l < r)
	    {
	    	min_height = min(height[l],height[r]);
		temp = min_height * (r - l);
		ans = ans > temp ? ans : temp;

		while(height[l] <= min_height && l < len)
			l ++;
		while(height[r] <= min_height && r >= 0)
			r --;
	    }

	    return	ans;
    }
};





原文地址:https://www.cnblogs.com/xz816111/p/5483433.html