LeetCode 0587. Erect the Fence Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0587. Erect the Fence

Description

You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.

Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed.

Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.

 

Example 1:

Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]
Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.

Example 2:

Input: trees = [[1,2],[2,2],[4,2]]
Output: [[4,2],[2,2],[1,2]]
Explanation: The fence forms a line that passes through all the trees.

 

Constraints:

  • 1 <= trees.length <= 3000
  • trees[i].length == 2
  • 0 <= xi, yi <= 100
  • All the given positions are unique.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def outerTrees(self, trees: List[List[int]]) -> List[List[int]]: def cross(i, j, k): a, b, c = trees[i], trees[j], trees[k] return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) n = len(trees) if n < 4: return trees trees.sort() vis = [False] * n stk = [0] for i in range(1, n): while len(stk) > 1 and cross(stk[-2], stk[-1], i) < 0: vis[stk.pop()] = False vis[i] = True stk.append(i) m = len(stk) for i in range(n - 2, -1, -1): if vis[i]: continue while len(stk) > m and cross(stk[-2], stk[-1], i) < 0: stk.pop() stk.append(i) stk.pop() return [trees[i] for i in stk](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !