Skip to content

Commit 9bd1922

Browse files
authored
feat: add typescript solution to lc problem: No.0042.Trapping Rain Water (doocs#527)
1 parent 5f90c65 commit 9bd1922

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

solution/0000-0099/0042.Trapping Rain Water/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,36 @@ class Solution {
102102
}
103103
```
104104

105+
### **TypeScript**
106+
107+
```ts
108+
function trap(height: number[]): number {
109+
let ans = 0;
110+
let left = 0, right = height.length - 1;
111+
let maxLeft = 0, maxRight = 0;
112+
while (left < right) {
113+
if (height[left] < height[right]) {
114+
// move left
115+
if (height[left] >= maxLeft) {
116+
maxLeft = height[left];
117+
} else {
118+
ans += (maxLeft - height[left]);
119+
}
120+
++left;
121+
} else {
122+
// move right
123+
if (height[right] >= maxRight) {
124+
maxRight = height[right];
125+
} else {
126+
ans += (maxRight - height[right]);
127+
}
128+
--right;
129+
}
130+
}
131+
return ans;
132+
};
133+
```
134+
105135
### **C++**
106136

107137
```cpp

solution/0000-0099/0042.Trapping Rain Water/README_EN.md

+30
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,36 @@ class Solution {
8484
}
8585
```
8686

87+
### **TypeScript**
88+
89+
```ts
90+
function trap(height: number[]): number {
91+
let ans = 0;
92+
let left = 0, right = height.length - 1;
93+
let maxLeft = 0, maxRight = 0;
94+
while (left < right) {
95+
if (height[left] < height[right]) {
96+
// move left
97+
if (height[left] >= maxLeft) {
98+
maxLeft = height[left];
99+
} else {
100+
ans += (maxLeft - height[left]);
101+
}
102+
++left;
103+
} else {
104+
// move right
105+
if (height[right] >= maxRight) {
106+
maxRight = height[right];
107+
} else {
108+
ans += (maxRight - height[right]);
109+
}
110+
--right;
111+
}
112+
}
113+
return ans;
114+
};
115+
```
116+
87117
### **C++**
88118

89119
```cpp
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function trap(height: number[]): number {
2+
let ans = 0;
3+
let left = 0, right = height.length - 1;
4+
let maxLeft = 0, maxRight = 0;
5+
while (left < right) {
6+
if (height[left] < height[right]) {
7+
// move left
8+
if (height[left] >= maxLeft) {
9+
maxLeft = height[left];
10+
} else {
11+
ans += (maxLeft - height[left]);
12+
}
13+
++left;
14+
} else {
15+
// move right
16+
if (height[right] >= maxRight) {
17+
maxRight = height[right];
18+
} else {
19+
ans += (maxRight - height[right]);
20+
}
21+
--right;
22+
}
23+
}
24+
return ans;
25+
};

0 commit comments

Comments
 (0)