LeetCode——max-points-on-a-line

本文介绍了一个算法问题:给定二维平面上的n个点,如何找到共线点的最大数量。通过穷举法解决该问题,考虑了多种特殊情况,如点的数量小于等于2的情况、点重合的情况以及如何计算斜率来判断点是否共线。
Question

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

Solution

这道题用穷举法求解,时间复杂度为O(n^2)。但是要注意几个细节,如果包含的点数小于等于2,那么直接返回点数。

如果第三个点和前面两个点中的一个相等,那么直接在总数上累加1。如果第三个点和前面两个点的横坐标都一样,那么直接在总数上累加1,如果只和其中一个一样,那么直接计算下一个点。如果两个都不一样,那么就开始计算斜率是否相等,相等的话,总数就累加1,反之。

Code
/**
 * 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();
        
        int maxNumbers = 2;
        for (int i = 0; i < points.size(); i++) {
            for (int j = i + 1; j < points.size(); j++) {
                int count = 2;
                for (int k = 0; k < points.size(); k++) {
                    if (k == i || k == j)
                        continue;
                    // 重叠
                    if ((points[k].x == points[i].x && points[k].y == points[i].y) || 
                        (points[k].x == points[j].x && points[k].y == points[j].y)) {
                        count++;
                        if (count > maxNumbers)
                            maxNumbers = count;
                        continue;
                    }
                    
                    // 横坐标一样,相减为0,不能计算斜率
                    if (points[k].x == points[j].x) {
                        if (points[j].x == points[i].x) {
                            count++;
                            if (count > maxNumbers)
                                maxNumbers = count;
                            continue;
                        } else
                            continue;
                    } else if (points[j].x == points[i].x) {
                        continue;
                    }
                    
                    // 计算斜率
                    if ((points[k].y - points[j].y) / (float)(points[k].x - points[j].x) ==
                       (points[j].y - points[i].y) / (float)(points[j].x - points[i].x))
                        count++;
                    if (count > maxNumbers)
                        maxNumbers = count;
                }
            }
        }
        return maxNumbers;
    }
};

转载于:https://www.cnblogs.com/zhonghuasong/p/7087469.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值