面试题16.14直线

给定一个二维平面及平面上的 N 个点列表Points,其中第i个点的坐标为Points[i]=[Xi,Yi]。请找出一条直线,其通过的点的数目最多。

设穿过最多点的直线所穿过的全部点编号从小到大排序的列表为S,你仅需返回[S[0],S[1]]作为答案,若有多条直线穿过了相同数量的点,则选择S[0]值较小的直线返回,S[0]相同则选择S[1]值较小的直线返回。

示例:

输入: [[0,0],[1,1],[1,0],[2,0]]
输出: [0,2]
解释: 所求直线穿过的3个点的编号为[0,2,3]
class Solution {
public:
    vector<int> bestLine(vector<vector<int>>& points) {
        int len = points.size();
        int max_point = 0;
        vector<int> res(2, 0);
        for(int i = 0; i < len; ++i){
            for(int j = i + 1; j < len; ++j){
                int count = 2;
                long x1 = points[i][0] - points[j][0];
                long y1 = points[i][1] - points[j][1];
                for(int k = j + 1; k < len; ++k){
                    long x2 = points[i][0] - points[k][0];
                    long y2 = points[i][1] - points[k][1];
                    if(x1 * y2 == x2 * y1){
                        ++count;
                    }
                }
                if(count > max_point){
                    max_point = count;
                    res[0] = i;
                    res[1] = j;
                }
                
            }
        }
        return res;

    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43599304/article/details/121282819