149. Max Points on a Line
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode149 Max Points on a Line