当前位置:网站首页>Daily question -1232 Dotted line

Daily question -1232 Dotted line

2022-06-09 11:00:00 Programmed ape without hair loss 2

subject

Given an array  coordinates , among  coordinates[i] = [x, y] , [x, y]  The abscissa is x、 Ordinate for y  The point of . Please judge , Whether these points belong to the same line in the coordinate system .

Example 1:
image.png

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

image.png

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

Tips :

2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates  There are no repeating points in

java Code :

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
 /*
        *    General style :Ax+By+C=0(AB≠0)
        *    Two point formula :(y-y1)/(x-x1)=(y-y2)/(x-x2)  ( Straight line crossing point (x1,y1),(x2,y2))
        */

        //  The fixed point here is coordinates[0], and coordinates[n-1]
        //  To avoid Division , Here we use “ The product of two inner terms is equal to the product of two outer terms ” Calculation 
        int n = coordinates.length;
        for(int i = 1; i < n-1; ++i)
        {
            if(
                (coordinates[i][0] - coordinates[0][0])*    /* (x-x1)*(y-y2) */
                (coordinates[i][1] - coordinates[n-1][1])
                !=
                (coordinates[i][1] - coordinates[0][1])*    /* (y-y1)*(x-x2) */
                (coordinates[i][0] - coordinates[n-1][0])

            )   return false;
        }
        return true;
    }
}
原网站

版权声明
本文为[Programmed ape without hair loss 2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091013189903.html