zoukankan      html  css  js  c++  java
  • leetcode-[3]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

    思路:最多的点,必然是点连成线时,所有斜率相同的最多的组合情况;

         那么如果不在同一直线点的组合也可能斜率相同,找其中一点与其它点连即可。

    #include <iostream>
    #include <vector>
    #include <map>
    
    using namespace std;
    
    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) {
            if (points.size() < 2)
                return points.size();
    
            int result = 0;
            for (int i = 0; i < points.size(); i++) {
                map<pair<int, int>, int> line;
    
                int overlap = 0, vertical = 0, curMax = 0;
                for (int j = i + 1; j < points.size(); j++)    {
                    if((points[i].x == points[j].x) && 
                       (points[i].y == points[j].y)) {
                        overlap ++;
                        continue;
                    }
                    else if (points[i].x == points[j].x) {
                        vertical ++;
                    }
                    else {
                        int dx = points[i].x - points[j].x;    
                        int dy = points[i].y - points[j].y;    
    
                        int gcd = GCD(dx, dy);
        
                        dx /= gcd;
                        dy /= gcd;
                        
                        line[make_pair(dx, dy)]++;
                        curMax = max(line[make_pair(dx, dy)], curMax);    
                    }
                    curMax = max(vertical, curMax);
                }
                result = max(result, curMax+overlap+1);
            }        
            return result;
        }
    
        int GCD(int a, int b) {
            if (b == 0)
                return a;
            return GCD(b, a%b);
        }
    };
    
    int main() {
        vector<Point> points;
    
        points.push_back(Point(3, 4));
        points.push_back(Point(3, 4));
        points.push_back(Point(3, 4));
        Solution *solution = new Solution();
        cout << solution->maxPoints(points) << endl;
    
        // (3,10),(0,2),(0,2),(3,10)
        vector<Point> points2;    
        points2.push_back(Point(3, 10));
        points2.push_back(Point(0, 2));
        points2.push_back(Point(0, 2));
        points2.push_back(Point(3, 10));
        cout << solution->maxPoints(points2) << endl;
        
        return 0;
    }
  • 相关阅读:
    1.时间复杂度与空间复杂度分析
    数据结构与算法之重头再来
    MySQL时间字段与业务代码取出的时间不一致问题
    [redtiger]在线靶场level3
    win10 卡顿 MsMpEng.exe进程
    react 笔记 局部打印 print
    react table td 自动换行
    kali apt-get update release文件过期
    ubuntu怎么切换到root用户,切换到root账号方法
    winscp连接kali 使用预置密码验证 拒绝访问
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/3982778.html
Copyright © 2011-2022 走看看