1037-有效的回旋镖

Raphael Liu Lv10

给定一个数组 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

方法一:向量叉乘

计算从 points}[0] 开始,分别指向 points}[1] 和 points}[2] 的向量 \vec{v}_1 和 \vec{v}_2。「三点各不相同且不在一条直线上」等价于「这两个向量的叉乘结果不为零」:
\vec{v}_1 \times \vec{v}_2 \ne \vec{0

[sol1-Python3]
1
2
3
4
5
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
v1 = (points[1][0] - points[0][0], points[1][1] - points[0][1])
v2 = (points[2][0] - points[0][0], points[2][1] - points[0][1])
return v1[0] * v2[1] - v1[1] * v2[0] != 0
[sol1-C++]
1
2
3
4
5
6
7
8
class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
vector<int> v1 = {points[1][0] - points[0][0], points[1][1] - points[0][1]};
vector<int> v2 = {points[2][0] - points[0][0], points[2][1] - points[0][1]};
return v1[0] * v2[1] - v1[1] * v2[0] != 0;
}
};
[sol1-Java]
1
2
3
4
5
6
7
class Solution {
public boolean isBoomerang(int[][] points) {
int[] v1 = {points[1][0] - points[0][0], points[1][1] - points[0][1]};
int[] v2 = {points[2][0] - points[0][0], points[2][1] - points[0][1]};
return v1[0] * v2[1] - v1[1] * v2[0] != 0;
}
}
[sol1-C#]
1
2
3
4
5
6
7
public class Solution {
public bool IsBoomerang(int[][] points) {
int[] v1 = {points[1][0] - points[0][0], points[1][1] - points[0][1]};
int[] v2 = {points[2][0] - points[0][0], points[2][1] - points[0][1]};
return v1[0] * v2[1] - v1[1] * v2[0] != 0;
}
}
[sol1-C]
1
2
3
4
5
bool isBoomerang(int** points, int pointsSize, int* pointsColSize){
int v1[2] = {points[1][0] - points[0][0], points[1][1] - points[0][1]};
int v2[2] = {points[2][0] - points[0][0], points[2][1] - points[0][1]};
return v1[0] * v2[1] - v1[1] * v2[0] != 0;
}
[sol1-Golang]
1
2
3
4
5
func isBoomerang(points [][]int) bool {
v1 := [2]int{points[1][0] - points[0][0], points[1][1] - points[0][1]}
v2 := [2]int{points[2][0] - points[0][0], points[2][1] - points[0][1]}
return v1[0]*v2[1]-v1[1]*v2[0] != 0
}
[sol1-JavaScript]
1
2
3
4
5
var isBoomerang = function(points) {
const v1 = [points[1][0] - points[0][0], points[1][1] - points[0][1]];
const v2 = [points[2][0] - points[0][0], points[2][1] - points[0][1]];
return v1[0] * v2[1] - v1[1] * v2[0] != 0;
};

复杂度分析

  • 时间复杂度:O(1)。

  • 空间复杂度:O(1)。

 Comments
On this page
1037-有效的回旋镖