Java 7ms simple solution beats 99%


  • 0
    W
    public boolean isReflected(int[][] points) {
    	if (points == null || points.length == 0 || points[0].length != 2) return true;
    	
    	int maxX = Integer.MIN_VALUE;
    	int minX = Integer.MAX_VALUE;
    	
    	for (int[] point : points) {
    		if (point[0] > maxX) maxX = point[0];
    		if (point[0] < minX) minX = point[0];
    	}
    	
    	final int line = minX + maxX;
    	
    	Arrays.sort(points, new Comparator<int[]> () {
    		@Override
    		public int compare (int[] i1, int[] i2) {
    			if (i1[0] != i2[0]) return i1[0] - i2[0];
    			else if (2 * i1[0] > line) {
    				return i1[1] - i2[1];
    			} else return i2[1] - i1[1];
    		}
    	});
    	
    	int p1 = 0, p2 = points.length - 1;
    	while (p1 <= p2) {
    		if (points[p1][0] + points[p2][0] != line) return false;
    		if (points[p1][0] * 2 != line && points[p1][1] != points[p2][1]) return false;
    		while (p1 + 1 < points.length && points[p1][0] == points[p1 + 1][0] && points[p1][1] == points[p1 + 1][1]) p1++;
    		while (p2 - 1 >= 0 && points[p2][0] == points[p2 -1][0] && points[p2][1] == points[p2 - 1][1]) p2--;
    		p1++;
    		p2--;
    	}
    	
    	return true;
    }
    

    Actually I think this problem is similar as the TwoSum problem... One can also use HashSet to solve this problem.


Log in to reply
 

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