11 . 盛最多水的容器
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。画 n 条垂直线,使得垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
注意:你不能倾斜容器,n 至少是2。
最优解:
class Solution {
public:
int maxArea(vector<int>& height) {
int start=0;
int end=height.size()-1;
int result=0;
while(start<end)
{
int area=min(height[end],height[start])*(end-start);
result=max(result,area);
if(height[start]<=height[end])
start++;
else
end--;
}
return result;
}
};
42 . 接雨水
描述:
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
分析:
1,扫描一遍,找到那根柱子最高
2,以最高柱子为界,从左边扫描
3,以最高柱子为界,从右边扫描、
解法二:
class Solution {
public:
int trap(const vector<int>& A) {
const int n = A.size();
int max = 0; // 最高的柱子将数组分为两半
for (int i = 0; i < n; i++)
if (A[i] > A[max]) max = i;
int water = 0;
for (int i = 0, peak = 0; i < max; i++)
if (A[i] > peak) peak = A[i];
else water += peak - A[i];
for (int i = n - 1, top = 0; i > max; i--)
if (A[i] > top) top = A[i];
else water += top - A[i];
return water;
}
};
84 . 柱状图中最大的矩形
描述:
https://leetcode-cn.com/problems/largest-rectangle-in-histogram/description/
大神的解法:
class Solution {
public:
int largestRectangleArea(vector<int>& height) {
stack<int> s;
height.push_back(0);
int result = 0;
for (int i = 0; i < height.size(); ) {
if (s.empty() || height[i] > height[s.top()])
s.push(i++);
else {
int tmp = s.top();
s.pop();
result = max(result,
height[tmp] * (s.empty() ? i : i - s.top() - 1));
}
}
return result;
}
};