首页 > 代码库 > 149. Max Points on a Line
149. Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
要求是输入n个坐标点,输出最多有多少个点在同一条直线上。
代码提交如下:
1 int Solution::maxPoints(vector<Point>& points) 2 { 3 if (points.size()<=2) 4 { 5 return points.size(); 6 } 7 8 unsigned int max_line_nums = 0; 9 10 for (unsigned int i = 0;i < points.size(); i++) 11 { 12 slope_map same_line; 13 unsigned int same_line_nums = 0, 14 same_x_nums = 0, 15 same_y_nums = 0, 16 same_points_nums = 0; 17 for (unsigned int j = i + 1; j < points.size(); j++) 18 { 19 if (points[i].x == points[j].x && points[i].y == points[j].y) 20 { 21 ++same_points_nums; 22 } 23 else if (points[i].x == points[j].x) 24 { 25 ++same_x_nums; 26 } 27 else if (points[i].y == points[j].y) 28 { 29 ++same_y_nums; 30 } 31 else 32 { 33 double slope = ((double)points[i].y - (double)points[j].y)/((double)points[i].x - (double)points[j].x); 34 double b = points[i].y - slope * points[i].x; 35 36 same_line[slope][b]++; 37 same_line_nums = (same_line_nums < same_line[slope][b])?same_line[slope][b]:same_line_nums; 38 } 39 } 40 unsigned int tmp_max_line_nums = same_points_nums + max(same_line_nums, (same_x_nums < same_y_nums)?same_y_nums:same_x_nums); 41 max_line_nums = tmp_max_line_nums < max_line_nums ? max_line_nums:tmp_max_line_nums; 42 } 43 44 return max_line_nums + 1; 45 }
不足之处:
利用y = kx + b 可以将k和b存在一个map中,但是对于很大的数来说,精度会引起误差,使得两个不同的点被认为是同一个点。
149. Max Points on a Line
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。