[leetcode] 149. 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.


这道题给出平面坐标系上的n个点,找出一条直线最多穿过多少这些已知的点。题目难度为Hard。

乍看起来可能无从下手,不过通过直线坐标公式y=kx+b可以知道通过一个固定点的直线可以用它的斜率k区分。这样我们可以固定一个点,然后计算其他点和它确定的直线斜率,相同斜率的必定在同一条直线上。遍历所有点,通过斜率区分通过它的直线。遍历到后续的点时不必考虑它之前的点,因为这些直线已经检查过了。至此大家应该已经想到了用HashTable来解决问题,遍历每个点,将通过这个点的所有直线斜率存入HashTable,如果斜率存在说明在同一条直线上。

这里有两点需要注意:

  1. 题目没有说明所有点不重复,可能有重复的点;

  2. 平行y轴的直线没有斜率,不能存入HashTable,要特殊处理。

具体代码:

/**
 * 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 maxNum = 0;
        
        if(points.size() == 0) return 0;
	    if(points.size() == 1) maxNum = 1;

        for(int i=0; i<points.size(); i++) {
    		unordered_map<double, int> hash;
		    int sameX = 0;    //e.g. line x=5
		    int samePoint = 1;
            for(int j=i+1; j<points.size(); j++) {
    			if(points[i].x == points[j].x && points[i].y == points[j].y) {
    				samePoint++;
    			}
                else if(points[i].x == points[j].x) {
    				sameX++;
                }
                else {
                    double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
    				if(hash.find(k) == hash.end()) hash[k] = 1;
    				else hash[k]++;
                }
            }
    		for(auto it = hash.begin(); it != hash.end(); it++) {
    		    maxNum = max(maxNum, it->second + samePoint);
    		}
    		maxNum = max(maxNum, sameX + samePoint);
        }
            
        return maxNum;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值