【面試準備】letcode—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.

#include <iostream>
#include <vector>
#include <map>
using namespace std;

struct Point{
	int x;
	int y;
	Point(): x(0),y(0){}
	Point(int a,int b):x(a),y(b){}
};

int maxPoints(vector<Point> &points){
	map<float,int> Points_k;
	int maxNum = 0;
	float k ;
	for(int i = 0 ; i < (signed)points.size() ; ++i){
		Points_k.clear();
		Points_k[INT_MIN] = 0;
		int num = 1;
		for(int j = 0; j < (signed)points.size() ; ++j){
			if( j == i){
				continue ;
			}
			if(points.at(i).x == points.at(j).x && points.at(i).y == points.at(j).y){
				num++;
				continue ;
			}
			k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x);
			Points_k[k]++;
		}
		map<float,int>::iterator iter;
		for(iter = Points_k.begin();iter != Points_k.end(); iter++){
			if(iter->second+num > maxNum){
				maxNum = iter->second + num;
			}
		}
	}
	return maxNum;
}

int main(){
	Point array[] = {Point(1,1),Point(2,2),Point(0,0),Point(50,-17)};
	vector<Point> points(array,array+4);
	cout<<maxPoints(points)<<endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章