LeetCode - 1232. 缀点成线

描述

在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。

请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。

示例 1:

输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
输出:true
示例 2:

输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
输出:false
 

提示:

2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates 中不含重复的点

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/

求解

方法二参考  https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/solution/san-dian-xiang-chai-zhi-bi-li-chao-99-by-co4x/

    struct PairPointsCompare {
        bool operator()(const vector<int> &lhs, const vector<int> &rhs) {
            if (lhs[0] != rhs[0]) {
                return lhs[0] < rhs[0];
            }
            return lhs[1] < rhs[1];
        }
    };

    class Solution {
    public:
        // 方法一,暴力解法,对点按照X轴排序后依次对两点求取夹角
        bool checkStraightLine_1e(vector<vector<int>> &coordinates) {
            std::sort(coordinates.begin(), coordinates.end(), PairPointsCompare());
            int l = 0;
            int r = coordinates.size() - 1;
            double angle = accAngel(coordinates[l], coordinates[r]);
            const double DIFF = 1E-6;
            while (++l < --r) {
                double diff = accAngel(coordinates[l], coordinates[r]) - angle;
                if ((diff < -DIFF) || (diff > DIFF)) {
                    return false;
                }
            }
            if (l == r) {
                double diff = accAngel(coordinates[0], coordinates[l]) - angle;
                return (diff > -DIFF) && (diff < DIFF);
            }
            return true;
        }

        // 方法二,通过斜率相同转换公式,三个点数据进行比较,去除浮点数计算
        bool checkStraightLine(vector<vector<int>> &coordinates) {
            const int n = coordinates.size();
            for (int i = 1; i < n - 1; ++i) {
                // 如果只有两个点,一定是一条直线,所以不进入该循环没有任何问题
                if (((coordinates[i + 1][1] - coordinates[i][1]) * (coordinates[i][0] - coordinates[i - 1][0])) !=
                    ((coordinates[i][1] - coordinates[i - 1][1]) * (coordinates[i + 1][0] - coordinates[i][0]))) {
                    return false;
                }
            }
            return true;
        }

    private:
        inline double accAngel(const vector<int> &point1, const vector<int> &point2) {
            int xDiff = point2[0] - point1[0];
            if (xDiff == 0) {
                return 720.0; // 给一个无效夹角值
            }
            return double(point2[1] - point1[1]) / xDiff;
        }
    };

猜你喜欢

转载自blog.csdn.net/u010323563/article/details/112734105