Count Number of Triples in an array that are collinear

后端 未结 6 789
梦谈多话
梦谈多话 2021-02-01 09:31

I was asked this Interview Question (C++,algos)and had no idea how to solve it.

Given an array say Arr[N] containing Cartesian coordinates of N distinct points count the

6条回答
  •  难免孤独
    2021-02-01 09:51

    Instead of 3 loops, whish is O(n³), precompute the slopes of all lines given by two points Arr[P], Arr[Q]. That's O(n²). Then compare these slopes.

    You can improve that further sorting the lines by their slope during computation or afterwards, which is O(n log n). After that finding lines with the same slope is O(n).

    But you may have to pay a price for that by implementing a data structure, when you want to know, which points are collinear.

    I think the key point of an interview question is not to give the perfect algorithm, but to identify and discuss the problems within an idea.

    Edit:

    Brute force approach:

    #include 
    #include 
    
    struct Point { int x, y; };
    bool collinear(Point P, Point Q, Point R)
    {
      // TODO: have to look up for math ... see icCube's answer
      return false; 
    }
    
    int main()
    {
      std::vector v;
    
      Point a;
      while (std::cin >> a.x >> a.y)
      {
        v.push_back(a);
      }
    
      int count = 0;
      for (int p = 0; p < v.size(); ++p)
      {
        for (int q = p+1; q < v.size(); ++q)
        {
          for (int r = q+1; r < v.size(); ++r)
          {
            if (collinear(v[p], v[q], v[r])) ++count;
          }
        }  
      }
      std::cout << count << '\n';
      return 0;
    }
    

提交回复
热议问题