Job solution: Consider duplicated points


  • 0
    S

    The java code is a little bit lengthy compared to others if we consider the cases where duplicated points are allowed. For example, [[1,1],[-1,1],[1,1]] should return false;

    public class Solution {
        class Point {
            int x;
            int y;
            
            public Point(int x, int y) {
                this.x = x;
                this.y = y;
            }
            public boolean equals(Object point) {
                Point p = (Point) point;
                return x == p.x && y == p.y;
            }
            public int hashCode() {
                return Arrays.hashCode(new int[]{x, y});
            }
        }
        public boolean isReflected(int[][] points) {
            if(points == null || points.length == 0) return true;
            
            HashMap<Point, Integer> myMap = new HashMap<>();
            int minX = Integer.MAX_VALUE;
            int maxX = Integer.MIN_VALUE;
            
            for (int[] point:points) {
                minX = Math.min(minX, point[0]);
                maxX = Math.max(maxX, point[0]);
                
                Point newPoint = new Point(point[0], point[1]);
                myMap.put(newPoint, myMap.getOrDefault(newPoint, 0) + 1); 
            }
            
            int sum = minX + maxX;
            for (int[] point : points) {
                //the potential pairs of points;
                Point newPoint = new Point(point[0], point[1]);
                Point oppositePoint = new Point((sum - point[0]), point[1]);
                
                //if pair not found, return false;
                if (!myMap.containsKey(oppositePoint)) return false;
                
                //If a pair is found, decrease the number of each point in the pair
                if (myMap.get(newPoint) > 0 && myMap.get(newPoint) > 0) {
                    myMap.put(newPoint, myMap.get(newPoint) - 1);
                    myMap.put(oppositePoint, myMap.get(oppositePoint) - 1);
                }
            }
            
            //if there is still point remaning unpaired, return false
            for (int[] point : points) {
                Point newPoint = new Point(point[0], point[1]);
                if (myMap.get(newPoint) > 0) return false;
            }     
            return true;    
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.