https://leetcode.com/problems/valid-boomerang/
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]] Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]] Output: false
Note:
points.length == 3
points[i].length == 2
0 <= points[i][j] <= 100
Assuming three points are A, B, C.
The first idea is that, calculate the area of ABC.
We can reuse the conclusion and prove in 812. Largest Triangle Area
We can reuse the conclusion and prove in 812. Largest Triangle Area
The other idea is to calculate the slope of AB and AC.
K_AB = (p[0][0] - p[1][0]) / (p[0][1] - p[1][1])
K_AC = (p[0][0] - p[2][0]) / (p[0][1] - p[2][1])
We check if
K_AB != K_AC
, instead of calculate a fraction.
Time
O(1)
Space O(1)
public boolean isBoomerang(int[][] p) {
return (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]) != (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]);
}
https://leetcode.com/problems/valid-boomerang/discuss/286666/Java-one-liner-slopes-of-2-edges-are-not-equal.
f the 3 points can form a triangle ABC, then the slopes of any 2 edges, such as AB and AC, are not equal.
Use Formula as follows:
(y0 - y1) / (x0 - x1) != (y0 - y2) / (x0 - x2) =>
(x0 - x2) * (y0 - y1) != (x0 - x1) * (y0 - y2)
Where
A:
x0 = p[0][0]
y0 = p[0][1]
B:
x1 = p[1][0]
y1 = p[1][1]
C:
x2 = p[2][0]
y2 = p[2][1]
A:
x0 = p[0][0]
y0 = p[0][1]
B:
x1 = p[1][0]
y1 = p[1][1]
C:
x2 = p[2][0]
y2 = p[2][1]
Use the muliplication form to cover corner cases such as, a slope is infinity, 2 or 3 points are equal.
public boolean isBoomerang(int[][] p) {
return (p[0][0] - p[2][0]) * (p[0][1] - p[1][1]) != (p[0][0] - p[1][0]) * (p[0][1] - p[2][1]);
}
https://www.cnblogs.com/seyjs/p/10824004.html
解题思路:本题就是判断三点是否在一条直线上,判断的方法也很简单,任意从这三个点中选取两组点对,如果这两组的点对的斜率相同,则在同一直线上。