leetcode-1232-easy

Check If it is a Straight Line

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

Example 1:



Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:



Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:

2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.

思路一:计算斜率,完全分类,1:斜率不存在;2:斜率存在,分别处理这两种情况

    public boolean checkStraightLine(int[][] coordinates) {
        double slope = getSlop(coordinates[0], coordinates[1]);

        if (slope == Double.MAX_VALUE) {
            for (int i = 1; i < coordinates.length; i++) {
                if (coordinates[i][0] != coordinates[0][0]) {
                    return false;
                }
            }
            return true;
        }

        for (int i = 2; i < coordinates.length; i++) {
            double temp = getSlop(coordinates[i], coordinates[i - 1]);

            if (slope != temp) {
                return false;
            }
        }

        return true;
    }

    public double getSlop(int[] a, int[] b) {
        int deltaY = a[1] - b[1];
        int deltaX = a[0] - b[0];
        if (deltaX != 0D) {
            return (double) deltaY / (double) deltaX;
        } else {
            return Double.MAX_VALUE;
        }
    }

思路二:避免除法运算,(y2-y1)/(x2-x1) = (y2-y0)/(x2-x0) = (y2-y1)(x2-x0) = (x2-x1)(y2-y0)


posted @ 2023-05-18 20:25  iyiluo  阅读(12)  评论(0)    收藏  举报