Skip to content

Commit 9f6b18f

Browse files
committedMar 6, 2025
Add solution #587
1 parent 1be62bc commit 9f6b18f

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,7 @@
455455
576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium|
456456
581|[Shortest Unsorted Continuous Subarray](./0581-shortest-unsorted-continuous-subarray.js)|Medium|
457457
583|[Delete Operation for Two Strings](./0583-delete-operation-for-two-strings.js)|Medium|
458+
587|[Erect the Fence](./0587-erect-the-fence.js)|Hard|
458459
589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy|
459460
594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy|
460461
599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy|

‎solutions/0587-erect-the-fence.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 587. Erect the Fence
3+
* https://leetcode.com/problems/erect-the-fence/
4+
* Difficulty: Hard
5+
*
6+
* You are given an array trees where trees[i] = [xi, yi] represents the location of
7+
* a tree in the garden.
8+
*
9+
* Fence the entire garden using the minimum length of rope, as it is expensive. The
10+
* garden is well-fenced only if all the trees are enclosed.
11+
*
12+
* Return the coordinates of trees that are exactly located on the fence perimeter.
13+
* You may return the answer in any order.
14+
*/
15+
16+
/**
17+
* @param {number[][]} trees
18+
* @return {number[][]}
19+
*/
20+
var outerTrees = function(trees) {
21+
const a = [];
22+
const b = [];
23+
24+
trees.sort(([x1, y1], [x2, y2]) => x1 === x2 ? y1 - y2 : x1 - x2);
25+
for (const point of trees) {
26+
while (a.length >= 2 && cross(a[a.length - 2], a[a.length - 1], point) < 0) {
27+
a.pop();
28+
}
29+
a.push(point);
30+
while (b.length >= 2 && cross(b[b.length - 2], b[b.length - 1], point) > 0) {
31+
b.pop();
32+
}
33+
b.push(point);
34+
}
35+
36+
return [...new Set([...a, ...b].map(p => JSON.stringify(p)))].map(p => JSON.parse(p));
37+
38+
function cross(p, q, r) {
39+
return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
40+
}
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.