Skip to content

Commit 9b3eac1

Browse files
add: 增加2个算法
1 parent baed5e6 commit 9b3eac1

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/202308/arr/接雨水.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// 给定[0,1,0,2,1,0,1,3,2,1,2,1]
2+
3+
function rain(height) {
4+
let res = 0;
5+
let left = 0, right = height.length - 1;
6+
let leftMax = 0, rightMax = 0;
7+
while(left < right) {
8+
if(height[left] < height[right]) {
9+
leftMax = Math.max(leftMax, height[left])
10+
res += leftMax - height[left]
11+
++left
12+
}else {
13+
rightMax = Math.max(rightMax, height[right])
14+
res += rightMax - height[right]
15+
--right
16+
}
17+
}
18+
return res
19+
}
20+
21+
console.log(rain([0,1,0,2,1,0,1,3,2,1,2,1]))

src/202308/func/手写reduce.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Array.prototype.myReduce = function(callback, initialValue) {
2+
let accumulator = initialValue === undefined ? undefined : initialValue;
3+
for (let i = 0; i < this.length; i++) {
4+
if(accumulator === undefined) {
5+
accumulator = this[i]
6+
}else {
7+
accumulator = callback(accumulator, this[i], i, this)
8+
}
9+
}
10+
return accumulator
11+
}

0 commit comments

Comments
 (0)