|
36 | 36 | +------------------->
|
37 | 37 | 0 1 2 3 4 5 6</pre>
|
38 | 38 |
|
39 |
| - |
40 | 39 | ## 解法
|
41 | 40 |
|
42 | 41 | <!-- 这里可写通用的实现逻辑 -->
|
43 | 42 |
|
| 43 | +在平面上确定一个点 `points[i]`,其他点与 `point[i]` 可以求得一个斜率,斜率相同的点意味着它们与 `points[i]` 在同一条直线上。 |
| 44 | + |
| 45 | +所以可以用哈希表作为计数器,其中斜率作为 key,然后累计当前点相同的斜率出现的次数。斜率可能是小数,我们可以用分数形式表示,先求分子分母的最大公约数,然后约分,最后将“分子.分母” 作为 key 即可。 |
| 46 | + |
| 47 | +需要注意,如果平面上有和当前点重叠的点,如果进行约分,会出现除 0 的情况,那么我们单独用一个变量 duplicate 统计重复点的个数,重复点一定是过当前点的直线的。 |
| 48 | + |
44 | 49 | <!-- tabs:start -->
|
45 | 50 |
|
46 | 51 | ### **Python3**
|
47 | 52 |
|
48 | 53 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
49 | 54 |
|
50 | 55 | ```python
|
51 |
| - |
| 56 | +class Solution: |
| 57 | + def maxPoints(self, points: List[List[int]]) -> int: |
| 58 | + def gcd(a, b) -> int: |
| 59 | + return a if b == 0 else gcd(b, a % b) |
| 60 | + |
| 61 | + n = len(points) |
| 62 | + if n < 3: |
| 63 | + return n |
| 64 | + res = 0 |
| 65 | + for i in range(n - 1): |
| 66 | + counter = collections.Counter() |
| 67 | + t_max = duplicate = 0 |
| 68 | + for j in range(i + 1, n): |
| 69 | + delta_x = points[i][0] - points[j][0] |
| 70 | + delta_y = points[i][1] - points[j][1] |
| 71 | + if delta_x == 0 and delta_y == 0: |
| 72 | + duplicate += 1 |
| 73 | + continue |
| 74 | + g = gcd(delta_x, delta_y) |
| 75 | + d_x = delta_x // g |
| 76 | + d_y = delta_y // g |
| 77 | + key = f'{d_x}.{d_y}' |
| 78 | + counter[key] += 1 |
| 79 | + t_max = max(t_max, counter[key]) |
| 80 | + res = max(res, t_max + duplicate + 1) |
| 81 | + return res |
52 | 82 | ```
|
53 | 83 |
|
54 | 84 | ### **Java**
|
55 | 85 |
|
56 | 86 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
57 | 87 |
|
58 | 88 | ```java
|
59 |
| - |
| 89 | +class Solution { |
| 90 | + public int maxPoints(int[][] points) { |
| 91 | + int n = points.length; |
| 92 | + if (n < 3) { |
| 93 | + return n; |
| 94 | + } |
| 95 | + int res = 0; |
| 96 | + for (int i = 0; i < n - 1; ++i) { |
| 97 | + Map<String, Integer> kCounter = new HashMap<>(); |
| 98 | + int max = 0; |
| 99 | + int duplicate = 0; |
| 100 | + for (int j = i + 1; j < n; ++j) { |
| 101 | + int deltaX = points[i][0] - points[j][0]; |
| 102 | + int deltaY = points[i][1] - points[j][1]; |
| 103 | + if (deltaX == 0 && deltaY == 0) { |
| 104 | + ++duplicate; |
| 105 | + continue; |
| 106 | + } |
| 107 | + int gcd = gcd(deltaX, deltaY); |
| 108 | + int dX = deltaX / gcd; |
| 109 | + int dY = deltaY / gcd; |
| 110 | + String key = dX + "." + dY; |
| 111 | + kCounter.put(key, kCounter.getOrDefault(key, 0) + 1); |
| 112 | + max = Math.max(max, kCounter.get(key)); |
| 113 | + } |
| 114 | + res = Math.max(res, max + duplicate + 1); |
| 115 | + } |
| 116 | + return res; |
| 117 | + } |
| 118 | + |
| 119 | + private int gcd(int a, int b) { |
| 120 | + return b == 0 ? a : gcd(b, a % b); |
| 121 | + } |
| 122 | +} |
60 | 123 | ```
|
61 | 124 |
|
62 | 125 | ### **...**
|
|
0 commit comments