class Solution
{
public List<Point> outerTrees(Point []points)
{
int firstIndex = 0;
Point firstP = points[0];
for(int i=0; i<points.length; i++)
{
if(points[i].x < firstP.x)
{
firstIndex = i;
firstP = points[i];
}
}
Set<Point> set = new HashSet<>();
set.add(firstP);
Point curP = firstP;
int curIndex = firstIndex;
do{
Point nextP = points[0];
int nextIndex = 0;
for(int i=1; i<points.length; i++)
{
if(i == curIndex) continue;
int cross = crossProduct(curP, nextP, points[i]);
if(nextIndex==curIndex || cross>0 ||
(cross==0&&distance(curP, points[i])>distance(curP, nextP)))
{
nextP = points[i];
nextIndex = i;
}
}
for(int i=0; i<points.length; i++)
{
if(i == curIndex) continue;
int cross = crossProduct(curP, nextP, points[i]);
if(cross == 0) set.add(points[i]);
}
curP = nextP;
curIndex = nextIndex;
}while(curIndex != firstIndex);
return new ArrayList<Point>(set);
}
public int crossProduct(Point A, Point B, Point C)
{
int ABx = B.x - A.x;
int ABy = B.y - A.y;
int ACx = C.x - A.x;
int ACy = C.y - A.y;
return ABx*ACy - ABy*ACx;
}
public int distance(Point A, Point B)
{
return (A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y);
}
}
求点集凸包
最新推荐文章于 2024-02-26 10:36:51 发布