1. 程式人生 > >二維平面求一條直線經過的最大點數

二維平面求一條直線經過的最大點數

題目:

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

問題描述:在一個二維平面上有n個點,求出現在同一直線上的點的最大個數

分析:對每一個點計算與其他點(不包括與該點相同的點)連線成的直線的斜率,斜率重複出現的最大次數加成該點重複出現的個數,即為該點所在直線上擁有的最大點個數(比如該點既出現在直線L1上,又出現在直線L2上,直線L1上有這n個點中的3個點,直線L2上有這n個點中的5個點,我們得到的該點所處直線的擁有最多點的那一條直線上的點個數便是5,有點繞口~~)。

對每一個點進行相同的操作,便可得到n個點中出現在同一直線的點的最大個數。

實現:

/**
 * 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:
   bool inOneLine(Point p1, Point p2, Point p3)
     {
         return ((p3.y-p1.y)*(p2.x-p1.x) == (p2.y-p1.y)*(p3.x-p1.x));
     }
     bool equal(Point p1, Point p2)
     {
         return (p1.x == p2.x || p1.y == p2.y);
     }
    int maxPoints(vector<Point> &points) {
         if(points.size() <= 2)
         {
               return points.size();
         }
          int ans = 2;
          int n = points.size();
          for(int i = 0; i < n-1; i ++)
          {
              for(int j = i+1; j < n; j ++)   
              {
                  int sum = 0;
                  if(equal(points[i], points[j]))
                  {
                      for(int k = 0; k < n; k ++)
                      {
                          if(equal(points[i], points[k]))
                          {
                              sum ++;
                          }
                      }
                  }
                  else 
                  {
                      for(int k = 0; k < n; k ++)
                      {
                          if(inOneLine(points[i], points[j], points[k]))
                          {
                              sum ++;
                          }
                     }
                 }
                 ans = max(ans, sum);
              }
          }
         return ans;
    }
};