checkStraightLine- dotted into a line

Title

There are some points in an XY coordinate system. We use the array coordinates to record their coordinates respectively, where coordinates[i] = [x, y] represents the point with the abscissa as
x and the ordinate as y.

Please judge whether these points are on the same straight line in the coordinate system. If yes, return true, otherwise, return false.

Example 1:

Insert picture description here

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

Example 2:
Insert picture description here

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

prompt:

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

Related Topics Geometry Array Mathematics

Problem-solving ideas

Relatively simple, direct code demonstration

Code demo:

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
            if(coordinates.length==2)
                return true;
            //判断所求线是否垂直于x轴
           if(coordinates[1][0]==coordinates[0][0])
           {
               for (int i = 2; i < coordinates.length; i++) {
                   if(coordinates[i][0]!=coordinates[0][0])
                       return false;
               }
           }
           else
           {
               //求直线的斜率,如果两点的斜率一致,则可以保证在同一条直线上
               double a=(coordinates[1][1]-coordinates[0][1])*1.0/(coordinates[1][0]-coordinates[0][0]);
               for (int i = 2; i < coordinates.length; i++) {
                   double b = (coordinates[i][1] - coordinates[0][1])*1.0 / (coordinates[i][0] - coordinates[0][0]);
                   if(a!=b)
                       return false;
               }
           }

        return true;
    }
}

running result

The info
answer was successful:
execution time: 0 ms, defeating 100.00% of Java users
Memory consumption: 37.9 MB, defeating 82.88% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/112728383