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)?
Solution1:selfencode + Hashset
思路: first pass先求出中心线并将每个点存入hashset,second pass 看是否每个点在中心线的对面对应位置存在另一个点。
关于点存入hashset的方式:这里自己编码了。因为hashset的key必须是id型,不能直接存collection,但collection object可以通过hashCode转成id存入,如solution2.
Time Complexity: O(N) Space Complexity: O(N)
Solution2:list_hashcode + Hashset
思路: 思路同1,但实现上直接将collection 通过 hashCode转成id存入hashset
Solution1 Code:
class Solution {
public boolean isReflected(int[][] points) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
HashSet<String> set = new HashSet<>();
for(int[] p: points){
max = Math.max(max, p[0]);
min = Math.min(min, p[0]);
String str = p[0] + "a" + p[1];
set.add(str);
}
int sum = max + min;
for(int[] p: points){
String str = (sum - p[0]) + "a" + p[1];
if( !set.contains(str)) {
return false;
}
}
return true;
}
}
Solution2 Code:
class Solution2 {
public boolean isReflected(int[][] points) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
HashSet<Integer> set = new HashSet<>();
for(int[] p: points){
max = Math.max(max, p[0]);
min = Math.min(min, p[0]);
set.add(Arrays.hashCode(p));
}
int sum = max + min;
for(int[] p: points){
String str = (sum - p[0]) + "a" + p[1];
if(!set.contains(Arrays.hashCode(new int[]{sum - p[0], p[1]}))) {
return false;
}
}
return true;
}
}