Max Points on a Line

问题来自http://oj.leetcode.com/problems/max-points-on-a-line/

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.

问题定义为给定2维平面上N个点,找到处于同一直线上的最大点的数目。包括横竖线以及斜线。

思路:N个点,任意两点为一线,最多N^2条直线,处于同一直线的所有点的斜率相同。因此对所有的直线求得其斜率,并进行计数,找到最大。

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

 /*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) {
        if(points.size() <=2)
        	return points.size();
        else{
        	//N^2解法 求斜率slope并对其计数 
        	int maxPoints = 1;
        	
        	for(vector<Point>::size_type i = 0; i < points.size(); i++){
        		Point pi = points[i];
        		//same with pi
        		int maxSameWithI = 0;
        		//map 
        		map<double, int> slope_count;
        		
        		for(vector<Point>::size_type j=i+1; j < points.size(); j++){
        			Point pj = points[j];
        			double slope = 0.0;
					if(pi.x != pj.x){
						slope = (double)(pj.y-pi.y)/(double)(pj.x-pi.x);
						slope_count[slope]++;
					}
					else if(pi.y==pj.y){
						maxSameWithI++;
					}
					else{
						slope = numeric_limits<double>::max();
						slope_count[slope]++;
					}
        		}
        		
        		//find max
        		int max = maxSameWithI+1;
        		if(slope_count.size()!=0){
        			int maxSlopes = 0;
        			for(map<double,int>::iterator it = slope_count.begin(); it!=slope_count.end(); it++){
        				if(it->second > maxSlopes)
        					maxSlopes = it->second;
        			}
        			max += maxSlopes;
        		}
        		if(max > maxPoints)
        			maxPoints = max;
        	}
        	return maxPoints;
        }
    }
};

int main(int argc, char** argv){
	Solution s;
	vector<Point> points;
	Point p1(2,1);
	points.push_back(p1);
	Point p2(1,2);
	points.push_back(p2);
	Point p3(1,-1);
	points.push_back(p3);
	Point p4(2,0);
	points.push_back(p4);
	Point p5(3,-1);
	points.push_back(p5);
	Point p6(3,1);
	points.push_back(p6);
	Point p7(0,-2);
	points.push_back(p7);
	cout<<"maxPoints : "<<s.maxPoints(points)<<endl;
	
	return 0;
}
注:i 确定之后,与 i 相连的所有直线的斜率计算之后不再重复计算。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值