在 C++ 中检查它是否是直线

c++server side programmingprogramming更新于 2024/9/1 17:18:00

假设我们有一个由 (x, y) 坐标组成的数据点列表,我们必须检查数据点是否形成直线。因此,如果这些点像 [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)],那么它们就形成直线。

为了解决这个问题,我们将取每个连续数据点之间的差值,并找到斜率。对于第一个点,找到斜率。对于所有其他点,检查斜率是否相同。如果它们相同,则返回 true,否则返回 false

示例

让我们看下面的实现,以便更好地理解 −

#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)

相关文章