链接
题目
给定一个数组
points
,其中points[i] = [xi, yi]
表示 X-Y 平面上的一个点,如果这些点构成一个 回旋镖 则返回true
。
示例
示例 1:
输入:points = [[1,1],[2,3],[3,2]]
输出:true示例 2:
输入:points = [[1,1],[2,2],[3,3]]
输出:false
提示
points.length == 3
points[i].length == 2
0 <= xi, yi <= 100
思路
判断三个点是否构成一条直线,我们只要判断x2和x1之间的斜率k1,以及x3和x1之间的斜率k2是否相等即可,然而求斜率可能会出现分母为0的情况,因此我们将两个斜率除法转换成乘法,即判断(y2-y1)/(x2-x1)= (y3-y1)/(x3-x1)可以转变成判断(y2-y1)*(x3-x1)=(y3-y1)*(x2-x1)
C++ Code
class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
int x1 = points[1][0]-points[0][0];
int x2 = points[2][0]-points[0][0];
int y1 = points[1][1]-points[0][1];
int y2 = points[2][1]-points[0][1];
return x1*y2 != y1*x2;
}
};