forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1232_Check_if_its_a_Straight_line
45 lines (41 loc) · 1.3 KB
/
1232_Check_if_its_a_Straight_line
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// https://leetcode.com/problems/check-if-it-is-a-straight-line/
class Solution {
int x1=-1,x2=-1,y1=-1,y2=-1;
public boolean checkStraightLine(int[][] coordinates) {
if(coordinates.length<2)
return false;
x1 = coordinates[0][0];
y1 = coordinates[0][1];
x2 = coordinates[1][0];
y2 = coordinates[1][1];
for(int i=2;i<coordinates.length;i++) {
if(checkEquation(coordinates[i][0],coordinates[i][1])==false)
return false;
}
return true;
}
public boolean checkEquation(int x, int y) {
int lhs =0,rhs=0;
if(x1!=x2)
lhs = (int)((x-x1)/(x2-x1));
if(y1!=y2)
rhs = ((int)((y-y1)/(y2-y1)));
if(lhs == rhs || (lhs == 0 && x1==x) || (rhs==0 && y1==y))
return true;
else
return false;
}
}
// Other approach
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int x0 = coordinates[0][0], y0 = coordinates[0][1], x1 = coordinates[1][0], y1 = coordinates[1][1];
int dx = x1 - x0, dy = y1 - y0;
for (int[] co : coordinates) {
int x = co[0], y = co[1];
if (dx * (y - y1) != dy * (x - x1))
return false;
}
return true;
}
}