【1037. 有效的回旋镖】
来源:力扣(LeetCode)
描述:
给定一个数组 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
方法一:向量叉乘(高中数学)
代码:
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;}
};
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:10.1 MB, 在所有 C++ 提交中击败了10.74%的用户
复杂度分析
时间复杂度: O(1)。
空间复杂度: O(1)。
方法二:斜率比较(高中数学)
class Solution {
public:bool isBoomerang(vector<vector<int>>& points) {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];return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1);}
};
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:9.9 MB, 在所有 C++ 提交中击败了78.53%的用户
时间复杂度: O(1)
空间复杂度: O(1)
更多推荐
【1037. 有效的回旋镖】
发布评论