一、题目描述
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
二、题解
解题思路:
- 组成三角形(即三点组成的面积不为0)就认为他是回旋镖
- 利用直线方程,如果 ,则不是回旋镖
- 斜率方程:算出 的斜率,在算 的斜率,不相等即为回旋镖
(1)
/**
* @thought:三角形面积 != 0
* @date: 1/18/2020 10:06 AM
* @Execution info:
* ·执行用时 ms 击败了 % 的java用户
* ·内存消耗 MB 击败了 % 的java用户
* @Asymptotic Time Complexity:O()
*/
public boolean isBoomerang(int[][] points) {
// (1) 三点互相不能相同
if(points[0] == points[1] || points[1] == points[2] || points[2] == points[0])
return false;
int x1 = points[0][0], y1 = points[0][1];
int x2 = points[1][0], y2 = points[1][1];
int x3 = points[2][0], y3 = points[2][1];
// 注:浮点数的比较不要用> < ==,要用不等于
// 可优化的运算,(1)提取公因子 (2)将1/2进行通分。
return x1*y2 - x2*y1 + x2*y3 - x3*y2 + x3*y1 - x1*y3 != 0;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
(2) 斜率
/**
* @thought:斜率不相等,要考虑的三个问题
*
* x0-x1 x0-x2
* k1 = —————— != —————— = k2
* y0-y1 y0-y2
* (1)除法计算时除数不能为0;
* (2)斜率可能是浮点数所以要用 1.0 * 把计算结果转成浮点数;
* (3)两个浮点数比相同不能用等号,要用相减的差和0.0001的比大小来表示
*
* @date: 1/18/2020 10:33 AM
* @Execution info:
* ·执行用时 ms 击败了 % 的java用户
* ·内存消耗 MB 击败了 % 的java用户
* @Asymptotic Time Complexity:O()
*/
public boolean isBoomerang2(int[][] points) {
int x0 = points[0][0], y0 = points[0][1];
int x1 = points[1][0], y1 = points[1][1];
int x2 = points[2][0], y2 = points[2][1];
// (1) 三点互相不能相同
if(x0==x1&&y0==y1 || x2==x1&&y2==y1 || x0==x2&&y0==y2)
return false;
// (2) 除数不能为零
if(y0 == y1 || y1 == y2)
return y0!=y2;
return Math.abs(1.0 * (x0-x1)/(y0-y1) - 1.0 *(x0-x2)/(y0-y2)) > 0.0001;
}