149. 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.


This question is a very typical one using reversed thinking.
Two different way to start:

  • First one is pretty straight forward, calculate there are how many different lines on this 2D panel and count the points number on each line to get the max one.
  • Second one is a little bit difficult to consider. We take advantage of the principal: if we have a fixed point and a slope, then we can exactly define a line. So for each point, we keep a hashmap, using the line slope as its key, and the value is the number of points which fell onto the line except the duplicate points.
/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
int maxPoints(vector& points){
   if(points.size() <= 2) return points.size();
   int maxNum = 0;
   for(int i = 0; i < points.size(); i++){
     unordered_map map;
     map[INT_MAX] = 0;
     int duplicate = 1, resMax = 0;
     for(int j = i+1; j < points.size(); j++){
       if(points[j].x == points[i].x && points[j].y == points[i].y){
         duplicate++;
       }else{
         double slope = (points[j].x == points[i].x) ? INT_MAX : (double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
         map[slope]++;
         resMax = max(resMax,map[slope]);
       }
     }
     maxNum = max(maxNum,resMax+duplicate);
   }
   return maxNum;
 }

你可能感兴趣的:(149. Max Points on a Line)