用 C++ 检查是否是一条直线
假设我们有一份数据点列表,包含 (x, y) 坐标,我们需要检查这些数据点是否形成一条直线。所以如果这些点类似于 [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)],那么它们就形成一条直线。
为了解决这个问题,我们将计算每个连续数据点之间的差,并找出斜率。对于第一个点,找出斜率。对于所有其他点,检查斜率是否相同。如果它们相同,则直接返回真,否则返回假
示例
让我们看看以下实现,以获得更好的理解 −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int gcd(int a, int b){
return !b?a:gcd(b,a%b);
}
bool checkStraightLine(vector<vector<int>>& c) {
bool ans =true;
bool samex = true;
bool samey = true;
int a = c[1][0]-c[0][0];
int b = c[1][1]-c[0][1];
int cc = gcd(a,b);
a/=cc;
b/=cc;
for(int i =1;i<c.size();i++){
int x = c[i][0]-c[i-1][0];
int y = c[i][1]-c[i-1][1];
int z = gcd(x,y);
x/=z;
y/=z;
ans =ans &&(x == a )&& (y == b );
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> c = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}};
cout << ob.checkStraightLine(c);
}输入
[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
输出
1 (1 indicates true)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
html
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP