C++编程学习之LeetCode OJ

LeetCode OJ:
Max Points on a Line
Given n points on a 2D plan
#include<iostream>
#include<vector>
#include<map>
#include<float.h>
#define NUM 5
using namespace std;
 struct Point {
     int x;
     int y;
     Point() : x(0), y(0) {}
     Point(int a, int b) : x(a), y(b) {}
  };
 class Solution
 {
 public:
	 int maxPoint(vector<Point> &points)
	 {
		 map<float,int> m;// creat an empty map
		 float k=0;
		 int max=0;//set the maxmium number of points that lie on the same straight line is 0
		 //enumerate all points
		 for(vector<Point>::size_type i=0;i<points.size();i++)
			{
				if(points.size()==1)// if there is only a point
					return(1);
				m.clear();//clear m for the next round of data
				m[FLT_MIN]=0;//initialize m
				int count=1;
				for(vector<Point>::size_type j=0;j<points.size();j++)
				{  
					if(j==i)
						continue;
					else if(points[j].x==points[i].x&&points[j].y==points[i].y)//judge duplicate element
						count++;
					else 
						{
							if(points[j].x==points[i].x&&points[j].y!=points[j].y)//judge infinite slope
								k=FLT_MAX;
							else
								k=(float)(points[j].y-points[i].y)/(float)(points[j].x-points[i].x);//get the value of different slope
							++m[k];//count the number of times k(slope)occurs in the m(points)
						}		
				}
				map<float,int>::iterator it=m.begin();//traversal m
				while(it!=m.end())
					{
						//compare and then update max 
						if (it->second+count>max)
						{
							max=it->second+count;
						}
						it++;
					}
			}
		return(max);
	}
};
int main()
{
	vector<Point> points;
	Point p[NUM];
	cout<<"Number of points inputed:"<<NUM<<"\n";
	for(int i=0;i<NUM;i++)
		{
			cin>>p[i].x>>p[i].y;
			cout<<"\n";
			points.push_back(p[i]);
		}

	Solution ss; 
	cout<<ss.maxPoint(points)<<endl;	 
}

e, find the maximum number of points that lie on the same straight line.

你可能感兴趣的:(LeetCode,C++,map,iterator)