问题描述
小M正在玩一个几何游戏,给定一个二维平面上的三个点 points,其中每个点用坐标 points[i] = [xi, yi] 表示。如果三点构成一个回旋镖,则返回 true。回旋镖的定义是三点不在一条直线上,并且这三个点互不相同。
请你帮助小M判断这些点是否构成一个回旋镖。
测试样例
样例1:
输入:
points = [[1, 1], [2, 3], [3, 2]]
输出:True
样例2:
输入:
points = [[1, 1], [2, 2], [3, 3]]
输出:False
样例3:
输入:
points = [[0, 0], [1, 1], [1, 0]]
输出:True
解答:
#include <vector>
using namespace std;
bool solution(vector<vector<int>> &points) {
// 三个点互不相同
if (points[0] == points[1] || points[1] == points[2] ||
points[0] == points[2]) {
return false;
}
// 使用斜率公式检查是否在一条直线上
// 计算 (y2 - y1) * (x3 - x1) != (y3 - y1) * (x2 - x1)
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 - x1) != (y3 - y1) * (x2 - x1);
}
int main() {
vector<vector<int>> v1 = {{1, 1}, {2, 3}, {3, 2}};
vector<vector<int>> v2 = {{1, 1}, {2, 2}, {3, 3}};
vector<vector<int>> v3 = {{0, 0}, {1, 1}, {1, 0}};
cout << (solution(v1) == true) << endl; // 输出: 1 (True)
cout << (solution(v2) == false) << endl; // 输出: 1 (False)
cout << (solution(v3) == true) << endl; // 输出: 1 (True)
return 0;
}
if (points[0] == points[1] || points[1] == points[2] || points[0] == points[2]) {
return false;
}
这部分代码检查三个点是否互不相同。如果有任意两个点相同,则直接返回 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];
return (y2 - y1) * (x3 - x1) != (y3 - y1) * (x2 - x1);
这部分代码使用斜率公式来判断三个点是否在一条直线上。具体来说,它计算了两个向量的叉积:
- 向量1:从点1到点2,即
(x2 - x1, y2 - y1) - 向量2:从点1到点3,即
(x3 - x1, y3 - y1)
如果这两个向量的叉积不为零,则说明这三个点不在一条直线上,返回 true,否则返回 false。
代码结构
- 函数定义:
bool solution(vector<vector<int>> &points)是主要的函数,负责判断三个点是否构成回旋镖。 - 主函数:
int main()中定义了几个测试用例,并调用solution函数进行测试,输出结果。
工具运用
MarsCode AI,会更快速的检测你所报错的代码,进行修改,并提供推给你修改后的代码,更方便不用一个一个进行挑错,不会的情况下,可以选择MarsCode AI进行提示。