這道題初看要遍歷所有可能就能求解,但是複雜度要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;
}
};