LeetCode - Max Points on a Line

来源:互联网 发布:window版mysql如何删除 编辑:程序博客网 时间:2024/06/03 01:37

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.

/** * 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 result = 0;    for (int i = 0; i < points.size(); ++i) {std::unordered_map<string, int> number;int mx = 0;int same = 1;for (int j = i+1; j < points.size(); ++j) {    int x = points[j].x - points[i].x;    int y = points[j].y - points[i].y;    int g = gcd(x, y);    if (g !=0) {        x /= g;        y /= g;    mx = max(mx, ++number[to_string(x) + " " + to_string(y)]);    }    else {    same++;    continue;    }}result = max(result, (mx + same));    }    return result;    }        int gcd(int a, int b) {         return a? a/abs(a)*abs(gcd(b%a, a)) : b;    }};


0 0