一起来刷算法题

max-points-on-a-line

2019-05-08  本文已影响0人  cherryleechen

时间限制:1秒 空间限制:32768K

题目描述

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 num=points.size();
        if(num<2)
            return num;
        int count=0;
        for(int i=0;i<num-1;i++){
            map<pair<int,int>,int> m;
            int cnt=0,numSame=0;
            for(int j=i+1;j<num;j++){
                if((points[i].x==points[j].x)
                   &&(points[i].y==points[j].y)){
                    ++numSame;continue;
                }
                int dx=points[i].x-points[j].x;
                int dy=points[i].y-points[j].y;
                int g=maxGYS(dx,dy);
                dx/=g;dy/=g;
                cnt=max(cnt,++m[make_pair(dx,dy)]);
            }
            count=max(count,cnt+numSame+1);
        }
        return count;
    }
    int maxGYS(int a,int b){
        if(b==0)
            return a;
        return maxGYS(b,a%b);
    }
};

运行时间:8ms
占用内存:360k

上一篇下一篇

猜你喜欢

热点阅读