【LeetCode-Hard-1】【Max Points on a Line】【点集中最大共线数】

来源:互联网 发布:高中背单词软件 编辑:程序博客网 时间:2024/05/21 16:21

最近比较消沉。so,刷题玩。尽量保证2天至少一道题。

题目主要来自LeetCode Hard题目,以及Acceptance小于20%的Medium/Easy题目(目前共80题)。


第一道题149Max Points on a Line12.7%HardGiven n points on a 2D plane, find the maximum number of points that lie on the same straight line.

struct Point {int x;int y;}

找出2维点集中最大共线数

====================================================

思路:

1.两点确定一直线,判断第三点是否在直线上,这是基础方法,时间复杂度O(n^3);

2.在第二层循环中,把斜率存入hashMap<斜率,次数>中,因hashMap查找时间复杂度为O(1),可将时间复杂度优化为O(n^2);

3.小点集情况(leetcode测试集点数小于200),x/y都是int,因此对除法的优化比对时间复杂度的优化效果更好,优先考虑优化斜率相关计算。

陷阱:

1.重复点的处理。

====================================================

刷题时我的思路是不引入除法,于是与O(n^2)无缘。不过leetcode点集较小,算法运行时间居然比O(n^2)时间少一半(hashMap数据结构使用c++ stl,我直接用的c代码),可见算法和数据结构的选择也要试实际情况,并非单纯复杂度越低越好(这是在为自己的愚蠢找借口大笑)。

重复点处理可以通过duplicate变量记录重复点数来优化,因为是直接在leetcode上刷的题没用ide跑,格式没调,就不贴改成duplicate的代码了。重复点本身也是个小概率事件。

小点集:

int maxPoints(struct Point* points, int pointsSize) {    if(pointsSize < 3)        return pointsSize;    int count = 2;    for(int i=0;i<pointsSize;i++){        int x1 = points[i].x;        int y1 = points[i].y;        for(int j=i+1;j<pointsSize;j++){            int x2 = points[j].x;            int y2 = points[j].y;            //p1==p2,相同点的处理    if(x1==x2 && y1==y2){for(int last=pointsSize-1;last>j;last--){    if(x2==points[last].x && y2==points[last].y) continue;    struct Point swap = points[last];    points[last] = points[j];    points[j] = swap; x2 = points[j].x;    y2 = points[j].y; break;}    }            //共线判断            int temp = 2;for(int k=j+1;k<pointsSize;k++){int x = points[k].x;int y = points[k].y;if( (x-x1)*(y2-y1)==(y-y1)*(x2-x1) ){temp ++;}}if(temp > count){count = temp;}}}return count;}
运行结果:8ms

===========================================

大点集,网友代码16ms

class Solution {public:    int maxPoints(vector<Point>& points) {        unordered_map<float, int> slopes;        int maxp = 0, n = points.size();        for (int i = 0; i < n; i++) {            slopes.clear();            int duplicate = 1;            for (int j = i + 1; j < n; j++) {                if (points[j].x == points[i].x && points[j].y == points[i].y) {                    duplicate++;                    continue;                }                float slope = (points[j].x == points[i].x) ? INT_MAX :                               (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);                slopes[slope]++;            }            maxp = max(maxp, duplicate);            for (auto slope : slopes)                if (slope.second + duplicate > maxp)                     maxp = slope.second + duplicate;         }        return maxp;    }};

0 0