[AlgoExpert] Line Through Points

Line Through Points

  • Time : O(n^2)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <vector>
using namespace std;

string degree(int y1, int x1, int y2, int x2) {
int Y = y1 - y2, X = x1 - x2;
int sign = Y * X >= 0 ? 1 : -1;
Y = abs(Y), X = abs(X);
if(Y != 0 and X != 0) {
int gcd = __gcd(Y, X);
Y /= gcd; X /= gcd;
} else if(Y == 0) return "0#1";
else if(X == 0) return "1#0";
return (sign == -1 ? "-" : "+") + to_string(Y) + "#" + to_string(X);
}

int lineThroughPoints(vector<vector<int>> points) {
int n = points.size(), res = 0;
for(int i = 0; i < n; i++) {
unordered_map<string, int> mp;
for(int j = i + 1; j < n; j++) {
res = max(res, ++mp[degree(points[i][0], points[i][1], points[j][0], points[j][1])]);
}
}
return res + 1;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/line-through-points/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.