1232. Patches into lines (mathematical straight line problems)

LeetCode: 1232. Dotted into a line

Insert picture description here


Ideas provided: Interview Question 16.14. Best straight line (mathematical vector collinear)


Ideas:

  1. First move to the origin according to the first point, so that the straight line becomes a straight line passing through the origin. (Straight line general equation Ax + By + C == 0)
  2. The method of vector collinearity
    2.1 Three points collinear: Two points (x1, y1) (x2, y2) minus the third point (x0, y0) respectively, if x 1 ∗ y 2 = = x 2 ∗ y 1 x1 * y2 == x2 * y1x1y 2==x2y 1 is the three points collinear.


AC Code straight line general equation

class Solution {
    
    
    public boolean checkStraightLine(int[][] cd) {
    
    
        // 把直线变成过原点的 -> 查看后面点的 b 是不是为 0, 不是 0 的话就返回 false
        int len = cd.length;
        int a = cd[0][0], b = cd[0][1];
        int x0 = cd[1][0] - a, y0 = cd[1][1] - b;
        // 移动
        for(int i = 2; i < len; i++) {
    
    
            cd[i][0] -= a;
            cd[i][1] -= b;
            // 直线的一般方程: Ax + By + C = 0 >> 过原点 C == 0
            // 然后代入 x0 and y0 --> 得 A = y0, B = -x0
            if(y0 * cd[i][0] + -x0 * cd[i][1] != 0) return false;
        }
        
        return true;
    }
}





AC Code vector collinear method

class Solution {
    
    
    public boolean checkStraightLine(int[][] cd) {
    
    
        int len = cd.length;
        int x0 = cd[1][0] - cd[0][0];
        int y0 = cd[1][1] - cd[0][1];
        for(int i = 2; i < len; i++) {
    
    
            int x1 = cd[i][0] - cd[0][0];
            int y1 = cd[i][1] - cd[0][1];
            if(x0 * y1 != y0 * x1) return false;
        }

        return true;
    }
}



Guess you like

Origin blog.csdn.net/qq_43765535/article/details/112755317