149.max-points-on-a-line.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import java.util.HashMap;
  2. /**
  3. * Definition for a point.
  4. * class Point {
  5. * int x;
  6. * int y;
  7. * Point() { x = 0; y = 0; }
  8. * Point(int a, int b) { x = a; y = b; }
  9. * }
  10. */
  11. class Solution {
  12. class Pair {
  13. final int _1;
  14. final int _2;
  15. Pair(int _1, int _2) {
  16. this._1 = _1;
  17. this._2 = _2;
  18. }
  19. @Override
  20. public int hashCode() {
  21. int hash = 7;
  22. hash = 71 * hash + _1;
  23. hash = 71 * hash + _2;
  24. return hash;
  25. }
  26. @Override
  27. public boolean equals(Object obj) {
  28. if (this == obj) return true;
  29. if (!(obj instanceof Pair)) return false;
  30. Pair p = (Pair) obj;
  31. return p._1 == _1 && p._2 == _2;
  32. }
  33. }
  34. public int maxPoints(Point[] points) {
  35. int res = 0;
  36. for (int i = 0; i < points.length; i++) {
  37. HashMap<Pair, Integer> map = new HashMap<>();
  38. int cnt = 1;
  39. for (int j = 0; j < points.length; j++) {
  40. if (j == i) continue;
  41. Point p1 = points[i];
  42. Point p2 = points[j];
  43. if (p1.x == p2.x && p1.y == p2.y) {
  44. cnt++;
  45. continue;
  46. }
  47. Pair slope = getSlope(p1, p2);
  48. Integer freq = map.getOrDefault(slope, 0);
  49. map.put(slope, freq + 1);
  50. }
  51. int max = 0;
  52. for (Integer val : map.values()) {
  53. max = Math.max(max, val);
  54. }
  55. res = Math.max(res, max + cnt);
  56. }
  57. return res;
  58. }
  59. private Pair getSlope(Point p1, Point p2) {
  60. int dx = p1.x - p2.x;
  61. int dy = p1.y - p2.y;
  62. if (dx == 0) return new Pair(p1.x, 0);
  63. if (dy == 0) return new Pair(0, p1.y);
  64. int d = gcd(dx, dy);
  65. return new Pair(dx / d, dy / d);
  66. }
  67. private int gcd(int m, int n) {
  68. return n == 0 ? m : gcd(n, m % n);
  69. }
  70. }