题目:
对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
示例:
输入:[(0,0),(0,1)] 输出:2
输入:[(2,3),(3,3),(-5,3)] 输出:3
代码:
1 /** 2 * struct Point { 3 * int x; 4 * int y; 5 * }; 6 */ 7 8 class Solution { 9 public: 10 /** 11 * 12 * @param points Point类vector 13 * @return int整型 14 */ 15 int maxPoints(vector<Point>& points) { 16 int length = points.size(), count = 2; 17 if(length < 2) return length; 18 19 for(int i = 0; i < length - 1; i ++){ 20 21 for(int k = i + 1; k < length - 1; k ++){ 22 int site_x = points[i].x - points[k].x; 23 int site_y = points[i].y - points[k].y; 24 int temp = 0; 25 if(site_x == 0 && site_y == 0) 26 continue; 27 for(int j = 0; j < length; j ++){ 28 if( !site_x && points[i].x == points[j].x) 29 temp ++; 30 else if( !site_y && points[i].y == points[j].y ) 31 temp ++; 32 else if( ( points[i].x - points[j].x )*site_y == (points[i].y - points[j].y)*site_x ) 33 temp ++; 34 } 35 count = max(count,temp); 36 } 37 } 38 return count; 39 } 40 };
我的笔记:
利用穷举的方法,将数组中所有的点,进行两两匹配,并求出利用site_x / site_y 得到的斜率(不直接用除法是因为在除法中会出现除不尽的情况,所以这里用site_x 和 site_y来代替)。