-
Notifications
You must be signed in to change notification settings - Fork 0
/
587. Erect the Fence
56 lines (52 loc) · 1.76 KB
/
587. Erect the Fence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* https://leetcode.com/problems/erect-the-fence/description/
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
class Solution {
public List<Point> outerTrees(Point[] points) {
int size = points.length;
HashSet<Point> fence = new HashSet<>();
if (size < 4) {
return Arrays.asList(points);
}
int leftMost = 0;
for (int i = 0; i < size; i++) {
if (points[i].x < points[leftMost].x) {
leftMost = i;
}
}
int p = leftMost;
do {
int q = (p + 1) % size;
for (int i = 0; i < size; i++) {
if (orientation(points[p], points[i], points[q]) < 0) {
q = i;
}
}
for (int i = 0; i < size; i++) {
if (i != p && i != q && orientation(points[p], points[i], points[q]) == 0 && isBetween(points[p], points[i], points[q])) {
fence.add(points[i]);
}
}
fence.add(points[q]);
p = q;
}
while (p != leftMost);
return new ArrayList<Point>(fence);
}
private int orientation(Point lastInFence, Point current, Point anyOther) {
int scalarProduct = (current.x - lastInFence.x) * (anyOther.y - current.y) - (current.y - lastInFence.y) * (anyOther.x - current.x);
return scalarProduct;
}
private boolean isBetween(Point a, Point b, Point c) {
boolean b1 = ((a.x <= b.x) && (b.x <= c.x)) || ((b.x <= a.x) && (b.x >= c.x));
boolean b2 = ((a.y <= b.y) && (b.y <= c.y)) || ((b.y <= a.y) && (b.y >= c.y));
return b1 && b2;
}
}