Tuesday, April 1, 2014

Max Points on a Line @LeetCode

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
package leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* Solution: get a point, calculate slope with all other points to see the max points on a line for this point.(same slope)
* After calculate every points, the max value will be answer.
*
* map.put((double)Integer.MIN_VALUE, 1); hanlde duplicates like(0,0) (0,0). Actually, MIN_VALUE doesn't matter. just define it.
*
* map.put(k, 2); -- there's a new point + points[i] = 2
* 0.0 + slope --> as (double)0/-1 = -0.0, so here we use 0.0+-0.0 =0.0 to handle this problem, if not, there're 0.0, -0.0 (different).
*
* Two important thing in this problem.
* 1. x == x, slope = Integer.MAX_VALUE
* 2. duplicate points handling
*
* @author jeffwan
* @date Apr 1, 2014
*/
public class MaxPoints {
public static int maxPoints(Point[] points) {
if (points == null || points.length == 0) {
return 0;
}
HashMap<Double, Integer> map = new HashMap<Double, Integer>();
int max = 1; // points[i] itself
for (int i = 0; i < points.length; i++) {
map.clear();
map.put((double)Integer.MIN_VALUE, 1);
int dup = 0;
for (int j = i + 1; j < points.length; j++) {
if (points[j].x == points[i].x && points[j].y == points[i].y) {
dup++;
continue;
}
double k = points[j].x == points[i].x ? (double) Integer.MAX_VALUE:
0.0 + (double) (points[j].y - points[i].y) / (double) (points[j].x - points[i].x);
if (map.containsKey(k)) {
map.put(k, map.get(k) + 1);
} else {
map.put(k, 2);
}
}
// duplicate points should be counted in.
for (int x : map.values()) {
if (dup + x > max) {
max = dup + x;
}
}
}
return max;
}
/*********************************************************************************/
/*
* My wrong solution: use slope k as unique identifier. create a HashMap. Calculate all slope between two points.
* and then find the max value. solve equations n(n-1)/2 = max.
* But slope can't identify one line! parallel lines also have same slope! I also didn't handle x-x = 0 situation.
*/
public int maxPoints2(Point[] points) {
HashMap<Double, Integer> hashMap = new HashMap<Double, Integer>();
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
if (points[j].x - points[i].x == 0) {
continue;
}
double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
if (hashMap.containsKey(k)) {
hashMap.put(k, hashMap.get(k) + 1);
} else {
hashMap.put(k, 1);
}
}
}
int max = Integer.MIN_VALUE;
for (int x : hashMap.values()) {
max = Math.max(max, x);
}
// solve equations n(n-1)/2 = x
int i;
for (i = 0; i < points.length; i++) {
if (i * (i - 1) / 2 == max) {
break;
}
}
return i;
}
// Point Class
static class Point {
int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
}
view raw MaxPoints.java hosted with ❤ by GitHub

No comments:

Post a Comment