Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points.
Example 1:
Given points = [[1,1],[-1,1]]
, return true
.
Example 2:
Given points = [[1,1],[-1,-1]]
, return false
.
Follow up:
Could you do better than O(n2)?
Hint:
- Find the smallest and largest x-value for all points.
- If there is a line then it should be at y = (minX + maxX) / 2.
- For each point, make sure that it has a reflected point in the opposite side.
Solution1 sorting
Sort the points with its X value;
if two points has the same X value:
Find the middle of the maxX and minX, in the left of the middle, Y smaller comes first, in the right of the middle Y greater comes first so that we could make the points being sorted as symmetric as possible.
Also we need to handle the duplicate points and for the points in the middle line.
Code:
public class Solution {
public boolean isReflected(int[][] points) {
//x,y
if(points.length <= 1) return true;
int minX = points[0][0];
int maxX = points[0][0];
for(int[] p : points){
minX = Math.min(minX,p[0]);
maxX = Math.max(maxX,p[0]);
}
final int sum = minX + maxX;
Arrays.sort(points, new Comparator<int[]>(){
public int compare(int[] i1, int[] i2){
if(i1[0] == i2[0]){
if(2 * i1[0] > sum){
return i1[1] - i2[1];
} else {
return i2[1] - i1[1];
}
}
return i1[0] - i2[0];
}
});
int i = 0, j = points.length - 1;
while(i <= j){
if(points[i][0] + points[j][0] != sum){
return false;
} else {
if(points[i][0] == points[j][0]){
break; // handle points in the middle line
} else if(points[i][1] != points[j][1]){
return false;
}
} //handle duplicates
i++;
j--;
while(i <= j && isSame(i,i-1,points)){
i++;
}
while(i <= j && isSame(j,j+1,points)){
j--;
}
}
return true;
}
boolean isSame(int i, int j, int[][] points){
return points[i][0] == points[j][0] && points[i][1] == points[j][1];
}
}
Solution 2: hashSet.
We find the middle line first, add all the nodes into the Set and check whether each node has its pair in the set.
public class Solution {
public boolean isReflected(int[][] points) {
//x,y
if(points.length <= 1) return true;
int minX = points[0][0];
int maxX = points[0][0];
for(int[] p : points){
minX = Math.min(minX,p[0]);
maxX = Math.max(maxX,p[0]);
}
final int sum = minX + maxX;
HashSet<Integer> hs = new HashSet<>();
for(int[] p : points){
hs.add(Arrays.hashCode(p));
}
for(int[] p : points){
int[] pair = findPair(p,sum);
if(!hs.contains(Arrays.hashCode(pair))){
return false;
}
}
return true;
}
int[] findPair(int[] p, int sum){
if(2 * p[0] == sum) return p;
return new int[]{sum - p[0],p[1]};
}
}
A useful method Arrays.hashCode(int[]) could help to compute a unique hashcode for the int array.
Summary: I find this question really similar to Two Sum.....