class Solution {
public:
int trap(vector<int>& height) {
if (height.size() <= 2) {
return 0;
}
int n = height.size();
int result = 0;
int leftMax = height[0];
for (int i = 1; i < n - 1; i++) {
leftMax = max(leftMax, height[i]);
int rightMax = 0;
for (int j = i; j < n; j++) {
rightMax = max(rightMax, height[j]);
}
result += min(leftMax, rightMax) - height[i];
}
return result;
}
};
class Solution {
public:
int trap(vector<int>& height) {
vector<int> rightMaxs;
vector<int> leftMaxs;
int n = height.size();
int result = 0;
if (n <= 2) {
return 0;
}
int a = height[0];
int b = height[n-1];
for (int i = 0; i < n; i++) {
a = max(height[i], a);
leftMaxs.push_back(a);
}
for (int j = n - 1; j >= 0; j--) {
b = max(height[j], b);
rightMaxs.push_back(b);
}
reverse(rightMaxs.begin(), rightMaxs.end());
for (int i = 1; i < n - 1; i++) {
result += min(leftMaxs[i], rightMaxs[i]) - height[i];
}
return result;
}
};
更快的版本
不适用vector可变数组, 直接使用最基本的数组
注意数组的初始化, 不使用memset操作不能保证数组中的值为0, 可能是垃圾数据
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int result = 0;
if (n <= 2) {
return 0;
}
int rightMaxs[n];
memset(rightMaxs, 0, sizeof(rightMaxs));
int leftMaxs[n];
memset(leftMaxs, 0, sizeof(leftMaxs));
int a = height[0];
int b = height[n-1];
for (int i = 0; i < n; i++) {
a = max(height[i], a);
leftMaxs[i] = a;
}
for (int j = n - 1; j >= 0; j--) {
b = max(height[j], b);
rightMaxs[j] = b;
}
for (int i = 1; i < n - 1; i++) {
result += min(leftMaxs[i], rightMaxs[i]) - height[i];
}
return result;
}
};