[leetcode] 149. Max Points on a Line

来源:互联网 发布:semantic ui 怎么 js 编辑:程序博客网 时间:2024/04/19 12:21

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


这道题给出平面坐标系上的n个点,找出一条直线最多穿过多少这些已知的点。题目难度为Hard。

乍看起来可能无从下手,不过通过直线坐标公式y=kx+b可以知道通过一个固定点的直线可以用它的斜率k区分。这样我们可以固定一个点,然后计算其他点和它确定的直线斜率,相同斜率的必定在同一条直线上。遍历所有点,通过斜率区分通过它的直线。遍历到后续的点时不必考虑它之前的点,因为这些直线已经检查过了。至此大家应该已经想到了用HashTable来解决问题,遍历每个点,将通过这个点的所有直线斜率存入HashTable,如果斜率存在说明在同一条直线上。

这里有两点需要注意:

  1. 题目没有说明所有点不重复,可能有重复的点;

  2. 平行y轴的直线没有斜率,不能存入HashTable,要特殊处理。

具体代码:

/** * 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 maxNum = 0;                if(points.size() == 0) return 0;    if(points.size() == 1) maxNum = 1;        for(int i=0; i<points.size(); i++) {    unordered_map<double, int> hash;    int sameX = 0;    //e.g. line x=5    int samePoint = 1;            for(int j=i+1; j<points.size(); j++) {    if(points[i].x == points[j].x && points[i].y == points[j].y) {    samePoint++;    }                else if(points[i].x == points[j].x) {    sameX++;                }                else {                    double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);    if(hash.find(k) == hash.end()) hash[k] = 1;    else hash[k]++;                }            }    for(auto it = hash.begin(); it != hash.end(); it++) {        maxNum = max(maxNum, it->second + samePoint);    }    maxNum = max(maxNum, sameX + samePoint);        }                    return maxNum;    }};

0 0
原创粉丝点击