題意:
給出一個代表高度的數組,求出由它組成的形狀能儲存多少體積的水。(下例中藍色表示水)
思路:
本題有O(nlogn)排序解法和O(n)單調棧解法。
排序解法——從大到小的排序數字,然後按順序放置到數軸上。因爲儲水的高度取決於一段區間左右兩端最高的高度,所以處理高度的方式是從大到小。對於當前需要安放的數字,如果它在之前安放的最左和最右兩個位置之內,則答案中需要減去一部分(相當於它擠出了水…)如果它能擴充區間大小,則答案增加一定體積。
單調棧解法——假設我們維護一個單調遞減的棧,那麼以當前需要安放的數字爲右端點對能儲水多少呢?例如,[0, 6, 0, 4, 0, 2, 0, 5],這時5貢獻的答案爲:與2圍成 (2 - 0) * 1 的空間,與4圍成 (4 - 2) * 3 的空間,與6圍成 (5 - 4) * 5 的空間。
代碼:
/**
* 單調隊列版本 9ms
*/
class Solution {
public:
int trap(vector<int> &height) {
if (height.size() <= 2) {
return 0;
}
int top = 1;
int *ht = new int[height.size()];
int *id = new int[height.size()];
ht[0] = height[0];
id[0] = 0;
int ans = 0;
for (int i = 1; i < height.size(); ++i) {
if (height[i] == 0) {
continue;
}
int h = 0;
while (top > 0 && ht[top - 1] <= height[i]) {
ans += (min(ht[top - 1], height[i]) - h) * (i - id[top - 1] - 1);
h = min(ht[top - 1], height[i]);
--top;
}
if (top > 0) {
ans += (min(ht[top - 1], height[i]) - h) * (i - id[top - 1] - 1);
}
ht[top] = height[i];
id[top] = i;
++top;
}
return ans;
}
};
/**
* 排序版本 12ms
*/
class Solution {
public:
int trap(vector<int> &height) {
if (height.size() <= 2) {
return 0;
}
cmp *itm = new cmp[height.size()];
for (int i = 0; i < height.size(); ++i) {
itm[i].idx = i;
itm[i].val = height[i];
}
sort(itm, itm + height.size());
int ans = 0, l = itm[0].idx, r = itm[0].idx;
for (int i = 1; i < height.size(); ++i) {
if (itm[i].idx < l) {
ans += (l - itm[i].idx - 1) * itm[i].val;
l = itm[i].idx;
} else if (itm[i].idx > r) {
ans += (itm[i].idx - r - 1) * itm[i].val;
r = itm[i].idx;
} else {
ans -= itm[i].val;
}
}
return ans;
}
private:
struct cmp {
int idx, val;
bool operator<(const cmp f) const {
return val > f.val;
}
};
};