leetcode
题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:
Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | | o | o | o +-------------> 0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Output: 4 Explanation: ^ | | o | o o | o | o o +-------------------> 0 1 2 3 4 5 6
参考:https://zxi.mytechroad.com/blog/geometry/leetcode-149-max-points-on-a-line/
思路:
两层遍历,第一层按照每个点为基点,然后遍历后面的各点,把点放到以基点为顶点的射线上
用数据结构map<pair<int,int>,int>存储,key是一个pair,通过dx/dy表示射线的角度,value表示这个角度上的点个数
maxcnt记录出这个基点下得到的同一线上最多点个数
samep记录与这个基点相同的点个数
maxcnt+samep就是过这个基点的包含最多点的线上点的个数
记录以每个点为基点得到的最大点数
代码:
/** * Definition for a point. * 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 l = points.size(); int ans = 0; for(int i = 0 ; i < l;i++){ Point p1 = points[i]; std::map<std::pair<int,int>,int> count; int maxcnt = 0; int samep = 1; for(int j = i+1; j < l;j++){ Point p2 = points[j]; if(p1.x == p2.x && p1.y == p2.y){ samep++; }else{ maxcnt = max(maxcnt,++count[getslope(p1,p2)]); } } ans = max(ans,maxcnt + samep); } return ans; } private: std::pair<int,int> getslope(Point p1,Point p2){ int dx = p2.x - p1.x; int dy = p2.y - p1.y; if(dx == 0){ //同一垂线 return {p1.x,0}; } if(dy == 0){ //同一水平线 return {0,p1.y}; } int g = gcd(dx,dy); return {dx/g,dy/g}; } int gcd(int a,int b){ return b == 0 ? a:gcd(b,a%b); } };