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

思考:考虑以下几种情况:

1.points中0、1、2个点;

2.points含相同点如{[0,0],[0,0]},{[1,1],[1,1],[2,2],[2,2]}};

3.斜率为无穷。

 

/**

 * 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:

    int maxPoints(vector<Point> &points) {

        int n=points.size(); //point个数

        if(n<=2) return n;

        int i,j;

        int max=0;

        map<double,int> m; //每个point斜率集合

        for(i=0;i<n;i++)

        {

            m.clear();

			m[INT_MAX]=0; //斜率为无穷

			int samepoint=1; //相同点个数

            for(j=0;j<n;j++)

            {

				if(i==j) continue;

				if((points[j].x==points[i].x)&&(points[j].y==points[i].y)) samepoint++;

                else if(points[j].x==points[i].x) m[INT_MAX]++;

                else

                {

                    double k=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x); //斜率不为无穷	

                    if(m.find(k)==m.end()) m[k]=1;

					else m[k]++;

                }

            }

			map<double,int>::iterator iter;

			for(iter=m.begin();iter!=m.end();iter++)

			{

			//	cout<<iter->first<<" "<<iter->second+samepoint<<endl;

				if(iter->second+samepoint>max) max=iter->second+samepoint;

			}

        }

        return max;

    }

};

  

你可能感兴趣的:(LeetCode)