已知:
给定我们一个点的集合,找出其中是否存在四个点能构成一个矩形
思路:
这道题的思路,往简单了想,我是这么考虑的:一个矩形的四个点分为左上右上左下右下,我们遍历点集合的所有点,假设当前点是左上,找到满足要求的所有左下和右上,然后左下和右上配对产生右下,判断右下是否在点集合之中,如果存在,则返回“YES”,如果遍历完都不存在,就返回“NO”
/*
public class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
*/
public class Solution {
/**
* @param pointSet: The point set
* @return: The answer
*/
public String rectangle(Point[] pointSet) {
for (Point p : pointSet) {
if (calculate(p, pointSet)) {
return "YES";
}
}
return "NO";
}
private boolean calculate(Point p, Point[] pointSet) {
for (int i = 0; i < pointSet.length; i++) {
if (pointSet[i].x == p.x && pointSet[i].y < p.y) {
for (int j = 0; j < pointSet.length; j++) {
if (pointSet[j].x > p.x && pointSet[j].y == p.y) {
Point temp = new Point(pointSet[j].x, pointSet[i].y);
if (contain(pointSet, temp)) {
return true;
}
}
}
}
}
return false;
}
private boolean contain(Point[] pointSet, Point temp) {
for (Point p : pointSet) {
if (p.x == temp.x && p.y == temp.y) {
return true;
}
}
return false;
}
}