https://leetcode-cn.com/problems/max-points-on-a-line/submissions/

    • 搞一张map, key放的是斜率,value放的是共享这个斜率的点有多少个
    • key用什么类型? double吗? 不行,有精度损耗,分子分母约一个最大公约数,然后用字符串 “分子_分母” 的形式表示
      • 为什么要约成最简形式?
        • 因为6/10和3/5虽然是一样的,但是表示成字符串就不一样了6_10, 3_5
    • 或者用两张map
      • image.png
      • 第一Integer是所有的分子, 第二个map中的第一个Integer是分母, 第二个Integer是点数
    • 有单独两类需要单独处理
      • 和我共y的
      • 和我共x的

    image.png

    • 所以最后map里的最优者需要和这两个去pk

    注意,如果数组中有重复点的话,最后pk出来的这个最优者还要加上重复点的个数

    1. public int maxPoints(int[][] points) {
    2. if (points == null) {
    3. return 0;
    4. }
    5. if (points.length <= 2) {
    6. return points.length;
    7. }
    8. Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
    9. int result = 0;
    10. for (int i = 0; i < points.length; i++) {
    11. map.clear();
    12. int samePosition = 1;
    13. int sameX = 0;
    14. int sameY = 0;
    15. int line = 0;
    16. for (int j = i + 1; j < points.length; j++) {
    17. int x = points[j][0] - points[i][0];
    18. int y = points[j][1] - points[i][1];
    19. if (x == 0 && y == 0) {
    20. samePosition++;
    21. } else if (x == 0) {
    22. sameX++;
    23. } else if (y == 0) {
    24. sameY++;
    25. } else {
    26. int gcd = gcd(x, y);
    27. x /= gcd;
    28. y /= gcd;
    29. if (!map.containsKey(x)) {
    30. map.put(x, new HashMap<>());
    31. }
    32. if (!map.get(x).containsKey(y)) {
    33. map.get(x).put(y, 0);
    34. }
    35. map.get(x).put(y, map.get(x).get(y) + 1);
    36. line = Math.max(line, map.get(x).get(y));
    37. }
    38. }
    39. result = Math.max(result, Math.max(Math.max(sameX, sameY), line) + samePosition);
    40. }
    41. return result;
    42. }
    43. public int gcd(int a, int b) {
    44. return b == 0 ? a : gcd(b, a % b);
    45. }