forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_587.java
89 lines (76 loc) · 3.22 KB
/
_587.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.fishercoder.solutions;
import com.fishercoder.common.classes.Point;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class _587 {
public static class Solution1 {
/**
* credit: https://discuss.leetcode.com/topic/89323/java-solution-convex-hull-algorithm-gift-wrapping-aka-jarvis-march
* There are couple of ways to solve Convex Hull problem. https://en.wikipedia.org/wiki/Convex_hull_algorithms
* The following code implements Gift wrapping aka Jarvis march algorithm
* https://en.wikipedia.org/wiki/Gift_wrapping_algorithm and
* also added logic to handle case of multiple Points in a line
* because original Jarvis march algorithm assumes no three points are collinear.
* It also uses knowledge in this problem https://leetcode.com/problems/convex-polygon.
* Disscussion: https://discuss.leetcode.com/topic/70706/beyond-my-knowledge-java-solution-with-in-line-explanation
*/
public List<Point> outerTrees(Point[] points) {
Set<Point> result = new HashSet<>();
// Find the leftmost point
Point first = points[0];
int firstIndex = 0;
for (int i = 1; i < points.length; i++) {
if (points[i].x < first.x) {
first = points[i];
firstIndex = i;
}
}
result.add(first);
Point cur = first;
int curIndex = firstIndex;
do {
Point next = points[0];
int nextIndex = 0;
for (int i = 1; i < points.length; i++) {
if (i == curIndex) {
continue;
}
int cross = crossProductLength(cur, points[i], next);
if (nextIndex == curIndex || cross > 0
// Handle collinear points
|| (cross == 0 && distance(points[i], cur) > distance(next, cur))) {
next = points[i];
nextIndex = i;
}
}
// Handle collinear points
for (int i = 0; i < points.length; i++) {
if (i == curIndex) {
continue;
}
int cross = crossProductLength(cur, points[i], next);
if (cross == 0) {
result.add(points[i]);
}
}
cur = next;
curIndex = nextIndex;
} while (curIndex != firstIndex);
return new ArrayList<>(result);
}
private int crossProductLength(Point A, Point B, Point C) {
// Get the vectors' coordinates.
int BAx = A.x - B.x;
int BAy = A.y - B.y;
int BCx = C.x - B.x;
int BCy = C.y - B.y;
// Calculate the Z coordinate of the cross product.
return (BAx * BCy - BAy * BCx);
}
private int distance(Point p1, Point p2) {
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
}
}