1232. Check If It Is a Straight Line
leetcode easy
#array#csharp#easy#leetcode
Task
Вам дан массив координат, coordinates[i] = [x, y], где [x, y] - координаты точки. Проверьте, образуют ли эти точки прямую линию в плоскости XY.
Пример:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
C# solution
matched/originalpublic class Solution {
public bool CheckStraightLine(int[][] coordinates) {
int x0 = coordinates[0][0], y0 = coordinates[0][1];
int x1 = coordinates[1][0], y1 = coordinates[1][1];
foreach (var point in coordinates) {
int x = point[0], y = point[1];
if ((x1 - x0) * (y - y0) != (y1 - y0) * (x - x0)) {
return false;
}
}
return true;
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool CheckStraightLine(int[][] coordinates) {
int x0 = coordinates[0][0], y0 = coordinates[0][1];
int x1 = coordinates[1][0], y1 = coordinates[1][1];
foreach (var point in coordinates) {
int x = point[0], y = point[1];
if ((x1 - x0) * (y - y0) != (y1 - y0) * (x - x0)) {
return false;
}
}
return true;
}
}Java solution
matched/originalpublic class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int x0 = coordinates[0][0], y0 = coordinates[0][1];
int x1 = coordinates[1][0], y1 = coordinates[1][1];
for (int[] point : coordinates) {
int x = point[0], y = point[1];
if ((x1 - x0) * (y - y0) != (y1 - y0) * (x - x0)) {
return false;
}
}
return true;
}
}JavaScript solution
matched/originalvar checkStraightLine = function(coordinates) {
const [x0, y0] = coordinates[0];
const [x1, y1] = coordinates[1];
for (const [x, y] of coordinates) {
if ((x1 - x0) * (y - y0) !== (y1 - y0) * (x - x0)) {
return false;
}
}
return true;
};Go solution
matched/originalfunc checkStraightLine(coordinates [][]int) bool {
x0, y0 := coordinates[0][0], coordinates[0][1]
x1, y1 := coordinates[1][0], coordinates[1][1]
for _, coord := range coordinates {
x, y := coord[0], coord[1]
if (x1 - x0) * (y - y0) != (y1 - y0) * (x - x0) {
return false
}
}
return true
}Explanation
Algorithm
Определение наклона:
Вычисляем наклон между первыми двумя точками и используем его как эталон.
Проверка других точек:
Для всех остальных точек проверяем, совпадает ли наклон, образуемый этими точками с первой точкой, с эталонным наклоном.
Если все наклоны совпадают, то все точки лежат на одной прямой.
😎