简介
接雨水.
简单思路
排序, 依次选择最高的柱子,所围城的池塘高度
code
class Solution {
public:
struct zhuzi{
int height;
int index;
};
bool static cmp(const struct zhuzi &a, const struct zhuzi &b) {
return a.height > b.height;
}
int trap(vector<int>& height) {
if(height.size() < 2) {
return 0;
}
int sum = 0;
vector<struct zhuzi> zh;
int index = 0;
for(auto it : height) {
zh.push_back({it, index});
index++;
}
sort(zh.begin(), zh.end(), cmp);
vector<bool> check(zh.size(), false);
int minIndex = 0;
int maxIndex = 0;
for(int i =0; i < zh.size(); i++) {
if(i == 0) {
int a = zh[i].height;
int b = zh[i+1].height;
int abminH = min(a, b);
int aI = zh[i].index;
int bI = zh[i+1].index;
int minab = min(aI, bI);
minIndex = minab;
int maxab = max(aI, bI);
maxIndex = maxab;
for(int j = minab + 1; j < maxab; j++){
sum += abminH - height[j];
check[j] = true;
}
i++;
}else{
int c = zh[i].height;
int ci = zh[i].index;
if(ci >= minIndex && ci <= maxIndex ) {
continue;
}
if(ci < minIndex) {
for(int j = ci + 1; j < minIndex; j++) {
sum += c - height[j];
check[j] = true;
}
minIndex = ci;
}else if(ci > maxIndex){
for(int j = maxIndex + 1; j < ci; j++) {
sum += c - height[j];
check[j] = true;
}
maxIndex = ci;
}
}
}
return sum;
}
};
class Solution {
public int trap(int[] height) {
if(height == null || height.length == 0) {
return 0;
}
int ans = 0;
int size = height.length;
int [] left_max = new int[size];
int [] right_max = new int[size];
left_max[0] = height[0];
for(int i=1; i<size; i++){
left_max[i] = Math.max(height[i], left_max[i-1]);
}
right_max[size - 1] = height[size - 1];
for(int i = size - 2; i>=0; i--) {
right_max[i] = Math.max(height[i], right_max[i + 1]);
}
for(int i=1; i<size - 1; i++) {
ans += Math.min(left_max[i], right_max[i]) - height[i];
}
return ans;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》