use*_*682 12 algorithm lines points computational-geometry
给定定义n 2行的不同点的P = {p 1,...,p n },写一个算法,该算法在最坏的情况下找到具有最低斜率(最小绝对值)和时间复杂度的行.O(n*log(n))
基于y位置对点进行排序(使用任意数量的众所周知的算法,n log n time).按顺序浏览列表,从0到n - 1,比较每个点对的斜率与您发现的任何斜率到目前为止的最低斜率.(那是时候了).
总的来说,那将是O(n log n).
在伪代码中:
Let P be the list of points (this list starts at 1)
n = P.length
S = quicksort("a.y < b.y", P) // or some other O(n log n) algorithm
bestSlope = float.inf
let p1 and p2 be points
for i = 1 to n-1:
currSlope = abs((P[i].y - P[i+1].y) / (P[i].x - P[i+1].x))
if currSlope < bestSlope:
bestSlope = currSlope
p1 = P[i]
p2 = P[i+1]
Run Code Online (Sandbox Code Playgroud)
定理:
证明(矛盾):
有了这个定理,你可以清楚地使用@ Zshazz的算法来找到正确的对 - 因为它们将是最近的邻居 - 在O(n*log n)
.