zoukankan      html  css  js  c++  java
  • 力扣算法题—149Max Points on a line

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

    Example 1:

    Input: [[1,1],[2,2],[3,3]]
    Output: 3
    Explanation:
    ^
    |
    |        o
    |     o
    |  o  
    +------------->
    0  1  2  3  4
    

    Example 2:

    Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
    Output: 4
    Explanation:
    ^
    |
    |  o
    |     o        o
    |        o
    |  o        o
    +------------------->
    0  1  2  3  4  5  6
    

    NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

    Solution:

      直接求每个点与其他点的斜率,然后计算相同斜率的个数就行

      注意两点:

      一个是会有相同的点出现,另一个是斜率计算得到无穷和double比较相等的情况

     1 class Solution {
     2 public:
     3     int maxPoints(vector<vector<int>>& points) {
     4         if (points.size() < 3)return points.size();
     5         int res = 0;        
     6         for (int i = 0; i < points.size(); ++i)
     7         {
     8             int same = 1;
     9             for (int j = i + 1; j < points.size(); ++j)
    10             {
    11                 int cnt = 0;
    12                 long long int x1 = points[i][0], x2 = points[j][0];
    13                 long long int y1 = points[i][1], y2 = points[j][1];
    14                 if (x1 == x2 && y1 == y2) { ++same; continue; }
    15                 for (int k = 0; k < points.size(); ++k)
    16                 {
    17                     long long int x3 = points[k][0], y3 = points[k][1];
    18                     if ((x1*y2 + x2 * y3 + x3 * y1 - x3 * y2 - x2 * y1 - x1 * y3) == 0)
    19                         ++cnt;
    20                 }
    21                 res = max(res, cnt);
    22             }
    23             res = max(res, same);
    24         }
    25         return res;
    26     }
    27 };
  • 相关阅读:
    好用的 convert freestyle jenkins jobs to pipeline 插件使用
    MkDocs 搭建试用
    当前云安全问题&&一些想法
    asciidoctor 安装试用
    gradle asciidoc 使用
    apache phoenix 安装试用
    parceljs 基本使用———又一个前端构建工具
    tidb 集群扩容
    tidb 安装试用&&以及安装几个问题解决
    caddy quic 协议试用&& 几个问题
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11762302.html
Copyright © 2011-2022 走看看