刚刚找来一道题刷了一下,中间还是遇到了一些麻烦,下面就来好好总结一下。
具体题目如下:
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 iis 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.
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轴围成的最大面积。
解答如下:
方法一(暴力法1)
先用两个指针分别指向数组的两端,然后用两层for循环,先固定左边指针,遍历右边指针,紧接着依次循环遍历,直至找到最大的面积,并返回该值。当然这不是最优的办法。
这里有几点需要注意:①由于是要找到最大面积,所以第一层for循环的控制为 l < height.size(),第二层的for循环的控制为 l < r。②这里并不需要用到全局变量。
class Solution {
public:
int maxArea(vector<int>& height) {
int maxarea = 0;
int high = 0;
int width = 0;
for(int l = 0; l < height.size(); l++)
for (int r = height.size() - 1; l < r; r--) {
if(height[l] < height[r])
high = height[l];
else
high = height[r];
width = r - l;
if (maxarea < width*high)
maxarea = width*high;
}
return maxarea;
}
};
提交后的结果如下:
方法二(暴力法2)
两层for循环,均从头开始扫描。本方法中把
if(height[i] < height[j])
high = height[i];
else
high = height[j];
width = j - i;
if (maxarea < width*high)
maxarea = width*high;
简化成了
maxarea = max(maxarea, min(height[i], height[j])*(j - i));
但运行时间反而变长了
class Solution {
public:
int maxArea(vector<int>& height) {
int maxarea = 0;
for(int i = 0; i < height.size(); i ++)
for (int j = i + 1; j < height.size(); j ++) {
maxarea = max(maxarea, min(height[i], height[j])*(j - i));
}
return maxarea;
}
};
提交后的结果如下:
方法三(对撞指针法)
利用两个指针分别指向数组的两端,然后齐头并进计算面积,同时通过将两端指针对应的元素进行对比,将小元素对应的下标++(--),这样做的目的是为了找到比当前更大的面积,相反若将大元素对应的下标++(--),那么只会找到更小的面积。
class Solution {
public:
int maxArea(vector<int>& height) {
int maxarea = 0;
int l = 0;
int r = height.size() - 1;
while (l < r) {
maxarea = max(maxarea, min(height[l], height[r])*(r-l));
if(height[l] < height[r])
l++;
else
r--;
}
return maxarea;
}
};
提交后的结果如下:
方法四(对撞指针优化法)
首先,很显然第一条直线与最后一条直线所围成容器的面积的底最宽,其余可能围成容器的面积都不会比这宽,所以其余容器要想装更多的水,只有拥有更高的直线才行。故在得到了最宽容器的面积之后,以它两个高度的最小值为基准,在两端不断跳过比该最小值还小的直线,然后计算高度值满足条件的两直线围成的新容器面积,同时更新基准。一直重复,直到 l<r 即遍历完所有面积可能大的容器。
class Solution {
public:
int maxArea(vector<int>& height) {
int maxarea = 0;
int h = 0;
int l = 0;
int r = height.size() - 1;
while (l < r) {
h = min(height[l], height[r]);//更新基准
maxarea = max(maxarea, h*(r-l));
while(height[l] <= h) l++;
while(height[r] <= h) r--;
}
return maxarea;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。