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.
All points are in a straight line if the slope between every pair of consecutive points is the same. To avoid division and floating point issues, we use the cross product: for points (x0, y0), (x1, y1), (xi, yi), the vectors (x1-x0, y1-y0) and (xi-x0, yi-y0) should be collinear, i.e., (x1-x0)(yi-y0) == (y1-y0)(xi-x0).
classSolution {
publicbooleancheckStraightLine(int[][] c) {
int dx = c[1][0]- c[0][0], dy = c[1][1]- c[0][1];
for (int i = 2; i < c.length; i++) {
if (dx * (c[i][1]- c[0][1]) != dy * (c[i][0]- c[0][0]))
returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funcheckStraightLine(c: Array<IntArray>): Boolean {
val dx = c[1][0] - c[0][0]
val dy = c[1][1] - c[0][1]
for (i in2 until c.size) {
if (dx * (c[i][1] - c[0][1]) != dy * (c[i][0] - c[0][0]))
returnfalse }
returntrue }
}
1
2
3
4
5
6
7
classSolution:
defcheckStraightLine(self, c: list[list[int]]) -> bool:
dx, dy = c[1][0] - c[0][0], c[1][1] - c[0][1]
for i in range(2, len(c)):
if dx * (c[i][1] - c[0][1]) != dy * (c[i][0] - c[0][0]):
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfncheck_straight_line(c: Vec<Vec<i32>>) -> bool {
let dx = c[1][0] - c[0][0];
let dy = c[1][1] - c[0][1];
for i in2..c.len() {
if dx * (c[i][1] - c[0][1]) != dy * (c[i][0] - c[0][0]) {
returnfalse;
}
}
true }
}