Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

题目:Given n points on a 2D plane, find the maximum number 

of points that lie on the same straight line.(给的点是用vector保

存)

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */

思路:

构建双重for循环,相当于起始点与终点

一个起始点和斜率可以确定一条直线,用map<double, int>来保存对应的斜率与该直线上出现的点数的值

三种情况:重合点(用dup来保存),斜率不存在的垂直点(用vertical来保存),斜率可算的正常情况

class Solution {
public:
    int maxPoints(vector<Point> &points) {
  		int size = points.size();
  		if(size < 0)return -1;
  		if(size == 0)return 0;
  		if(size == 1)return 1;
  		map<double, int> mymap;
  		int res = 0; //the final result
  		for(int i = 0; i < size; ++i){
  			int vertical = 0;  //垂直点
  			int dup = 0;  //重合点duplicate
  			int curmax = 1;
  			for(int j = 0; j < size; ++j){
  				if(i != j){
  					double delt_x = points[i].x - points[j].x;  //delt_* must be declared double
  					double delt_y = points[i].y - points[j].y;
  					if((int)delt_y == 0 && (int)delt_x == 0){ //重合点
  						dup++;
  					}else if(delt_x == 0){ //垂直点
  						if(vertical == 0)vertical = 2;
  						else vertical++;
  						curmax = max(vertical, curmax);
  					}else{ //common situation
  						double k = delt_y / delt_x;
  						if(mymap[k] == 0)mymap[k] = 2;
  						else mymap[k]++;
  						curmax = max(mymap[k], curmax);
  					}
  				}
  			}
  			res = max(res, curmax+dup);
  		}
  		return res;
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值