Dotted line java

There are some points in an XY coordinate system. We use the array coordinates to record their coordinates separately, 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 中不含重复的点

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/check-if-it-is-a-straight-line
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

class Solution {
    
    
    public boolean checkStraightLine(int[][] coordinates) {
    
    
        int len = coordinates.length;
        if(len < 2) return true;
        
        //(y2 - y1) / (x2 - x1) == (y3 - y2) / (x3 - x2)
        //(y2 - y1) * (x3 - x2)  == (y3 - y2) * (x2 - x1)
        for(int i = 1; i < len -1 ; i++){
    
    
            int dx = coordinates[i][0] - coordinates[i-1][0];
            int dy = coordinates[i][1] - coordinates[i-1][1];

            int dx2 = coordinates[i+1][0] - coordinates[i][0];
            int dy2 = coordinates[i+1][1] - coordinates[i][1];

            if(1.0 * dy * dx2 != 1.0 * dy2 * dx) return false;
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/112746053