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

    经过同一个点且斜率相等的直线一定是同一条直线,所以我们只要分别计算每一个点与其它点的直线的斜率,统计斜率的个数,找出最大值。可以使用double来表示斜率,使用map<double, int>来统计个数。但是有两点要注意,那就是:

    (1) 如果直线与x轴垂直,此时斜率是无穷大,要单独处理

    (2) 所给的点中有些是相同的点,此时也要特殊处理一下。

     1 /**
     2  * Definition for a point.
     3  * struct Point {
     4  *     int x;
     5  *     int y;
     6  *     Point() : x(0), y(0) {}
     7  *     Point(int a, int b) : x(a), y(b) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxPoints(vector<Point>& points) {
    13         int res = 0, same_cnt, ver_cnt, cnt;
    14         unordered_map<double, int> mp;
    15         double k;
    16         for (int i = 0; i < points.size(); ++i) {
    17             same_cnt = ver_cnt = cnt = 0;
    18             mp.clear();
    19             for (int j = 0; j < points.size(); ++j) {
    20                 if (points[i].x == points[j].x) {
    21                     if (points[i].y == points[j].y) {
    22                         ++same_cnt; 
    23                         continue;
    24                     }else {
    25                         ++ver_cnt;
    26                         cnt = max(cnt, ver_cnt);
    27                     }
    28                 } else {
    29                     k = (double) (points[i].y - points[j].y) / (points[i].x - points[j].x);
    30                     ++mp[k];
    31                     cnt = max(cnt, mp[k]);
    32                 }
    33             }
    34             res = max(res, cnt + same_cnt);
    35         }
    36         return res;
    37     }
    38 };
  • 相关阅读:
    DevOps平台中的自动化部署
    GitLab的安装及使用教程
    Nginx配置相关
    Shell常用模块
    PostgreSQL基础
    大数据集群监控工具
    大数据常用组件
    kafka知识
    数据结构可视化(包括红黑树动态演示)
    python 周考1
  • 原文地址:https://www.cnblogs.com/easonliu/p/4527792.html
Copyright © 2011-2022 走看看