1
+ // 这道题目很显然可以使用立方的时间复杂度,常数的空间复杂度来解决
2
+ // 但是,可以使用哈希表牺牲空间来换取时间
3
+
4
+ // Runtime: 24 ms, faster than 41.41% of C++ online submissions for Max Points on a Line.
5
+ // Memory Usage: 12.6 MB, less than 24.54% of C++ online submissions for Max Points on a Line.
6
+
7
+ class Solution
8
+ {
9
+ public:
10
+ int maxPoints (vector<vector<int >>& points)
11
+ {
12
+ // 边界条件处理
13
+ if (points.size () <= 2 ) return points.size ();
14
+
15
+ int res = 2 ;
16
+ for (int i = 0 ; i < points.size (); ++i)
17
+ {
18
+ int tempres = 0 , overlap = 0 ;
19
+ unordered_map<string, int > hashMap;
20
+
21
+ for (int j = i; j < points.size (); ++j)
22
+ {
23
+ if (points[i][0 ] == points[j][0 ] && points[i][1 ] == points[j][1 ])
24
+ {
25
+ ++overlap;
26
+ continue ;
27
+ }
28
+
29
+ string slope = getSlope (points[i], points[j]);
30
+ if (hashMap.find (slope) == hashMap.end ())
31
+ {
32
+ hashMap.insert (pair<string, int >(slope, 1 ));
33
+ tempres = max (tempres, 1 );
34
+ }
35
+ else
36
+ tempres = max (tempres, ++hashMap.at (slope));
37
+ }
38
+ res = max (res, tempres + overlap);
39
+ }
40
+ return res;
41
+ }
42
+ private:
43
+ string getSlope (const vector<int >& point1, const vector<int >& point2)
44
+ {
45
+ int a = point1[1 ] - point2[1 ];
46
+ int b = point1[0 ] - point2[0 ];
47
+
48
+ // 如果两点形成了一条垂线
49
+ if (b == 0 ) return to_string (point1[0 ]) + " *" ;
50
+
51
+ // 如果两点之间形成了一条水平线
52
+ if (a == 0 ) return " *" + to_string (point1[1 ]);
53
+
54
+ // 两点形成一条正常的线段
55
+ int gcd = getGcd (a, b);
56
+ a /= gcd, b /= gcd;
57
+
58
+ if ((a > 0 && b < 0 )|| (a < 0 && b < 0 ))
59
+ a *= -1 , b*= -1 ;
60
+ return to_string (a) + ' *' + to_string (b);
61
+ }
62
+
63
+ // 求取两数的最大公约数
64
+ int getGcd (int num1, int num2)
65
+ {
66
+ while (num1 % num2 != 0 )
67
+ {
68
+ int temp = num1 % num2;
69
+ num1 = num2;
70
+ num2 = temp;
71
+ }
72
+ return num2;
73
+ }
74
+ };
0 commit comments