First, let's talk about mathematics.
How to determine if three points are on the same line?
The answer is to see if slopes of arbitrary two pairs are the same.
Second, let's see what the minimum time complexity can be.
Definitely, O(n^2). It's because you have to calculate all slopes between any two points.
Given point A, we need to calculate all slopes between A and other points. There will be three cases:
Some other point is the same as point A.
Some other point has the same x coordinate as point A, which will result to a positive infinite slope.
General case. We can calculate slope.
We can store all slopes in a hash table. And we find which slope shows up mostly. Then add the number of same points to it. Then we know the maximum number of points on the same line for point A.
use hashmap, 計算相同的斜率的 count
重合的點要個別計算, 最後加到結果(題目後來有改過, 現在所有點都是 unique 的dy/dx 計算斜率, 需要除法, 這是不安全的, 用 double 存斜率是不可靠的, 精度不夠, 所以不真的計算 slope,
但不計算 slope 的話, 需要先算出 dy, dx 的 GCD,
dy, dx 如果是互質, 都是最簡分數, 那算出來的斜率才會是 unique 的, 要達到互質: 做約分, 所以需要 GCD
int a = dy/ gcd(dy, dx)
int b = dx/ gcd(dy, dx)
然後直接拿 a, b 當成 key 來用, 不用計算 slope! 這裡直接拿 a +"," + b 當 hashmap key
如果用 double 像這樣, 差距微乎其微, double 計算出來的斜率會是一樣的
為什麼可以用斜率來求呢? 三點想要共線 (a, b,c), 固定一個點, 一定有兩對斜率是一樣的(a,b 斜率 跟 a, c 斜率一樣), 所以需要兩兩去比較, 所以 time complexity 會是 O(n^2)
T: O(n^2), n is number of points
S: O(n)
有計算重複的點的版本:
no duplicate:
Last updated
Was this helpful?