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 看是否每個點在中心線的對面對應(yīng)位置存在另一個點。
關(guān)于點存入hashset的方式:這里自己編碼了。因為hashset的key必須是id型,不能直接存collection,但collection object可以通過hashCode轉(zhuǎn)成id存入,如solution2.
Time Complexity: O(N) Space Complexity: O(N)

Solution2:list_hashcode + Hashset

思路: 思路同1,但實現(xiàn)上直接將collection 通過 hashCode轉(zhuǎn)成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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Given n points on a 2D plane, find if there is such a lin...
    Jeanz閱讀 348評論 0 0
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,927評論 0 33
  • 從來知道堅持是什么,但從未認(rèn)真的堅持自己。在殘忍的社會中,深深的認(rèn)識到了,所謂的差距,所謂的階級,所謂的理想。深深...
    nhsl閱讀 207評論 0 0
  • 今日讀書目標(biāo)檢視:和學(xué)生們分享《賴聲川的創(chuàng)意學(xué)》 健康目標(biāo)檢視:完成 家庭目標(biāo)檢視:和先生女兒一起去護(hù)老院幫忙,晚...
    晨曦曉林閱讀 225評論 0 0

友情鏈接更多精彩內(nèi)容