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.
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
if (coordinates.length == 2) return true;
Arrays.sort(coordinates, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) return o1[1] - o2[1];
return o1[0] - o2[0];
}
});
double lin = (double) (coordinates[1][0] - coordinates[0][0]) / (coordinates[1][1] - coordinates[0][1]);
for (int i = 1; i < coordinates.length - 1; i++) {
double next = (double) (coordinates[i + 1][0] - coordinates[i][0]) / (coordinates[i + 1][1] - coordinates[i][1]);
if (next != lin) return false;
}
return true;
}
}