solution.md 2.2 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
# 直线上最多的点数

<p>给你一个数组 <code>points</code> ,其中 <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> 表示 <strong>X-Y</strong> 平面上的一个点。求最多有多少个点在同一条直线上。</p>

<p> </p>

<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>输入:</strong>points = [[1,1],[2,2],[3,3]]
<strong>输出:</strong>3
</pre>

<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>输入:</strong>points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
<strong>输出:</strong>4
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>1 <= points.length <= 300</code></li>
	<li><code>points[i].length == 2</code></li>
	<li><code>-10<sup>4</sup> <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>4</sup></code></li>
	<li><code>points</code> 中的所有点 <strong>互不相同</strong></li>
</ul>


## template

```cpp
ToTensor's avatar
ToTensor 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#include <bits/stdc++.h>
using namespace std;

struct Point
{
    int x;
    int y;
    Point() : x(0), y(0) {}
    Point(int a, int b) : x(a), y(b) {}
};

class Solution
{
public:
    int maxPoints(vector<Point> &points)
    {
        int ans = 0;
        for (int i = 0; i < points.size(); ++i)
        {
            map<pair<int, int>, int> m;
            int p = 1;
            for (int j = i + 1; j < points.size(); ++j)
            {
                if (points[i].x == points[j].x && (points[i].y == points[j].y))
                {
                    ++p;
                    continue;
                }
                int dx = points[j].x - points[i].x;
                int dy = points[j].y - points[i].y;
                int d = gcd(dx, dy);
                ++m[{dx / d, dy / d}];
            }
            ans = max(ans, p);
            for (auto it = m.begin(); it != m.end(); ++it)
            {
                ans = max(ans, it->second + p);
            }
        }
        return ans;
    }
    int gcd(int a, int b)
    {
        return (b == 0) ? a : gcd(b, a % b);
    }
};
ToTensor's avatar
ToTensor 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110


```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```