356. Line Reflection

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given n points on a 2D plane, find if there is such a lin...
    Jeanz阅读 330评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • 从来知道坚持是什么,但从未认真的坚持自己。在残忍的社会中,深深的认识到了,所谓的差距,所谓的阶级,所谓的理想。深深...
    nhsl阅读 192评论 0 0
  • 今日读书目标检视:和学生们分享《赖声川的创意学》 健康目标检视:完成 家庭目标检视:和先生女儿一起去护老院帮忙,晚...
    晨曦晓林阅读 205评论 0 0