Max Points on a Line

来源:互联网 发布:将json对象遍历成数组 编辑:程序博客网 时间:2024/05/29 09:28

题目:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

解答:

遍历,注意重复节点和斜率为0的情况。

代码:

class Solution {public:int maxPoints(vector<Point> &points) {map<float, int> mp;int i, j;int same = 0;int max = 0;for (i = 0; i < points.size(); i++){same = 1;mp.clear();mp[INT_MAX] = 0;for (int j = 0; j < points.size(); j++){if (i == j)continue;if (points[i].x == points[j].x && points[i].y == points[j].y){same++;continue;  //这里 漏写continue,导致后面重复计算}float k = (points[i].x == points[j].x ? INT_MAX : (float)(points[i].y - points[j].y) / (float)(points[i].x - points[j].x));  //这里float k误写成int k 调试了一个小时,笨啊++mp[k];}for (map<float, int>::iterator it = mp.begin(); it != mp.end(); it++){if (it->second + same > max)max = it->second + same;}}return max;}};


0 0