Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Solution:

  1. /**
  2. * Definition for a point.
  3. * class Point {
  4. * int x;
  5. * int y;
  6. * Point() { x = 0; y = 0; }
  7. * Point(int a, int b) { x = a; y = b; }
  8. * }
  9. */
  10. public class Solution {
  11. public int maxPoints(Point[] points) {
  12. if (points == null || points.length == 0)
  13. return 0;
  14. int n = points.length, max = 1;
  15. Map<String, Set<Point>> map = new HashMap<String, Set<Point>>();
  16. // sort the points by x to avoid -0.0 issue!
  17. Collections.sort(Arrays.asList(points), new Comparator<Point>() {
  18. public int compare(Point a, Point b) { return a.x - b.x; }
  19. });
  20. for (int i = 0; i < n; i++) {
  21. for (int j = i + 1; j < n; j++) {
  22. Point p1 = points[i];
  23. Point p2 = points[j];
  24. StringBuilder sb = new StringBuilder();
  25. if (p1.x == p2.x) {
  26. sb.append("inf").append(p1.x);
  27. } else {
  28. // y = k * x + d
  29. double k = (double)(p1.y - p2.y) / (p1.x - p2.x);
  30. double d = p1.y - k * p1.x;
  31. sb.append("k").append(k).append("d").append(d);
  32. }
  33. String key = sb.toString();
  34. Set<Point> set = map.containsKey(key) ? map.get(key) : new HashSet<Point>();
  35. set.add(p1);
  36. set.add(p2);
  37. map.put(key, set);
  38. max = Math.max(max, set.size());
  39. }
  40. }
  41. return max;
  42. }
  43. }