Leetcode题解(十五)

时间:2023-03-09 08:32:21
Leetcode题解(十五)

42、Trapping Rain Water

题目

Leetcode题解(十五)

这道题目参考http://www.cnblogs.com/felixfang/p/3713197.html

观察下就可以发现被水填满后的形状是先升后降的塔形,因此,先遍历一遍找到塔顶,然后分别从两边开始,往塔顶所在位置遍历,水位只会增高不会减小,且一直和最近遇到的最大高度持平,这样知道了实时水位,就可以边遍历边计算面积。

代码如下:

 class Solution {
public:
int trap(vector<int>& height)
{
const int n = height.size();
if(n <= ) return ;
int max = -, maxInd = ;
int i = ;
for(; i < n; ++i){//找出最大值所在位置
if(height[i] > max){
max = height[i];
maxInd = i;
}
}
int area = , root = height[];
for(i = ; i < maxInd; ++i){
if(root < height[i]) root = height[i];
else area += (root - height[i]);//与最近的高点的高度差
}
for(i = n-, root = height[n-]; i > maxInd; --i){
if(root < height[i]) root = height[i];
else area += (root - height[i]);
}
return area;
} };

-----------------------------------------------------------------------------------------分割线-----------------------------------------------------------------------------------

43、Multiply Strings

题目

Leetcode题解(十五)

模拟乘法,代码如下:

 class Solution {
public:
string multiply(string num1, string num2) {
int len1 = num1.size(), len2 = num2.size(), len = len1 + len2;
string str(len, '');
for (int i = len1 - ; i >= ; i--)
{
int a = num1[i] - '';
for (int j = len2 - , k = len2 + i; j >= ; j--, k--)
{
int b = num2[j] - '';
int c = str[k] - '';
int t = b * a + c;
str[k] = t % + '';
int d = (str[k-] - '') + t / ;
if (d >= ) //开始这里没有等号,检查了很久才发现,细心啊细心
str[k-] = str[k-] - '' + d / + '';
str[k-] = d % + '';
}
}
int x = ;
while (str[x] == '')
x++;
if (str.substr(x, len - x) == "")
return "";
return str.substr(x, len - x); }
};