Erect the Fence LeetCode solution in JavaScript

1
const outerTrees = (trees) => {
2
trees.sort((x, y) => {
3
if (x[0] == y[0]) return x[1] - y[1];
4
return x[0] - y[0];
5
});
6
let lower = [],
7
upper = [];
8
for (const tree of trees) {
9
while (
10
lower.length >= 2 &&
11
cmp(lower[lower.length - 2], lower[lower.length - 1], tree) > 0
12
)
13
lower.pop();
14
while (
15
upper.length >= 2 &&
16
cmp(upper[upper.length - 2], upper[upper.length - 1], tree) < 0
17
)
18
upper.pop();
19
lower.push(tree);
20
upper.push(tree);
21
}
22
return [...new Set(lower.concat(upper))];
23
};
24

25
const cmp = (p1, p2, p3) => {
26
let [x1, y1] = p1;
27
let [x2, y2] = p2;
28
let [x3, y3] = p3;
29
return (y3 - y2) * (x2 - x1) - (y2 - y1) * (x3 - x2);
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0