这道题初看要遍历所有可能就能求解,但是复杂度要O(n^2),系统肯定会判超时。大概这么多年应试教育的结果吧,所以继续思考:很明显两边的情况是底最长,往中间缩的话有可能高度的变化会弥补底边的缩小,所以只考虑高度变长的情况即可。当两边确定后,需要从短的那边往中间缩进,就能遍历所有的可能了。当然每次缩进后都要重新判断短的那边。其实是求面积的问题,说成是装水,最终我还是打算返回矩形面积,应试教育的后果就是即使题出错了也能将错就错,最终给出出题人想要的答案。很激动的是这道题居然一次通过了,说明这道题难度系数不高。
class Solution {
public:
int maxArea(vector<int> &height) {
int length = height.size();
int left = height[0];
int right = height[length - 1];
bool shiftRight = false;
int maxArea = 0;
if (left < right) {
maxArea = left * (length - 1);
shiftRight = true;
}
else {
maxArea = right * (length - 1);
}
int index_left = 0;
int index_right = length - 1;
while (index_left < index_right) {
int newMax = 0;
if (shiftRight) {
if (height[++index_left] > left) {
left = height[index_left];
}
else {
continue;
}
}
else {
if (height[--index_right] > right) {
right = height[index_right];
}
else {
continue;
}
}
if (right > left) {
newMax = left * (index_right - index_left);
shiftRight = true;
}
else {
newMax = right * (index_right - index_left);
shiftRight = false;
}
maxArea = (newMax > maxArea) ? newMax : maxArea;
}
return maxArea;
}
};