原题连接:Leetcode 1037. Valid Boomerang
Given an array points
where points[i] = [xi, yi]
represents a point on the X-Y plane, return true
if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.
Example 1:
Input: points = [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: points = [[1,1],[2,2],[3,3]]
Output: false
Constraints:
- points.length == 3
- points[i].length == 2
- 0 <= xi, yi <= 100
方法一:向量叉乘
思路:
要判断3个点是否在同一直线上,想到向量叉乘。
由3个点组成两个向量,如果在同一条直线上,叉乘的结果为0
c++代码:
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;
}
};
复杂度分析:
- 时间复杂度:O(1)
- 空间复杂度:O(1)