149. Max Points on a Line
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