classSolution { public: boolcheckStraightLine(vector<vector<int>> &coordinates){ int deltaX = coordinates[0][0], deltaY = coordinates[0][1]; int n = coordinates.size(); for (int i = 0; i < n; ++i) { coordinates[i][0] -= deltaX; coordinates[i][1] -= deltaY; } int A = coordinates[1][1], B = -coordinates[1][0]; for (int i = 2; i < n; ++i) { int x = coordinates[i][0], y = coordinates[i][1]; if (A * x + B * y != 0) { returnfalse; } } returntrue; } };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funccheckStraightLine(coordinates [][]int)bool { deltaX, deltaY := coordinates[0][0], coordinates[0][1] for _, p := range coordinates { p[0] -= deltaX p[1] -= deltaY } A, B := coordinates[1][1], -coordinates[1][0] for _, p := range coordinates[2:] { x, y := p[0], p[1] if A*x+B*y != 0 { returnfalse } } returntrue }
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicbooleancheckStraightLine(int[][] coordinates) { intdeltaX= coordinates[0][0], deltaY = coordinates[0][1]; intn= coordinates.length; for (inti=0; i < n; i++) { coordinates[i][0] -= deltaX; coordinates[i][1] -= deltaY; } intA= coordinates[1][1], B = -coordinates[1][0]; for (inti=2; i < n; i++) { intx= coordinates[i][0], y = coordinates[i][1]; if (A * x + B * y != 0) { returnfalse; } } returntrue; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var checkStraightLine = function(coordinates) { const deltaX = coordinates[0][0], deltaY = coordinates[0][1]; const n = coordinates.length; for (let i = 0; i < n; i++) { coordinates[i][0] -= deltaX; coordinates[i][1] -= deltaY; } const A = coordinates[1][1], B = -coordinates[1][0]; for (let i = 2; i < n; i++) { const [x, y] = [coordinates[i][0], coordinates[i][1]]; if (A * x + B * y !== 0) { returnfalse; } } returntrue; };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
boolcheckStraightLine(int** coordinates, int coordinatesSize, int* coordinatesColSize) { int deltaX = coordinates[0][0], deltaY = coordinates[0][1]; for (int i = 0; i < coordinatesSize; ++i) { coordinates[i][0] -= deltaX; coordinates[i][1] -= deltaY; } int A = coordinates[1][1], B = -coordinates[1][0]; for (int i = 2; i < coordinatesSize; ++i) { int x = coordinates[i][0], y = coordinates[i][1]; if (A * x + B * y != 0) { returnfalse; } } returntrue; }