[leetcode]Max Points on a Line

来源:互联网 发布:php set 编辑:程序博客网 时间:2024/06/07 06:04

Problem Description

Link
在平面图上给出n个点,求最多有多少点在同一条直线上。

Possible Solution

暴力

枚举两个点,固定一条直线。枚举所有点,看有多少点在这条直线上。时间复杂度 O(n^3)

固定一点

固定一个点,枚举其他点,计算斜率,同一个斜率的一定在同一条直线上。复杂度O(n)
统计同一个斜率有多少点的时候,本来想构造一个hash表。后面发现太麻烦了 。其实只需要把每个斜率存下来,然后sort一下, 再判断有多少个重复的k即可。
附代码:

/** * Definition for a point. * struct Point { *     int x; *     int y; *     Point() : x(0), y(0) {} *     Point(int a, int b) : x(a), y(b) {} * }; */int ans;int dblcmp(double k) {    if (fabs(k)<1e-6) return 0;    if (k > 0) return 1;    return -1;}class Solution {public:  int maxPoints(vector<Point>& points) {    int n = points.size();    if (n == 0) return 0;    Point &p = points[0];    ans = 0;    vector<double> v;    int plus = 1;    for (int i = 1; i < n; ++i) {        Point &x = points[i];        if (x.x == p.x) {            if (x.y == p.y) ++plus;            else ++ans;        }        else {            double k = double(x.y-p.y)/(x.x-p.x);            v.push_back(k);        }    }    std::sort(v.begin(), v.end());    int m = v.size();    for (int i = 0; i < m; ++i) {        int j = i;        while (i+1 < m && dblcmp(v[i+1] - v[j]) == 0 ) ++i;        if (i-j+1 > ans) ans = i-j+1;    }    return ans+plus;  }};
0 0
原创粉丝点击