用 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