, , . , n+1 . , (, ), . , , P0, - Pn. , n+1, n.
- , (
minX) (maxX) x; - (
BitArray[max - min + 1]); - , ,
BitArray[minX + currentX] = true; int Distances[n] BitArray.- ,
minX; Distances[0] = thisX - minX;Distances.
O (maxX - minX), . O (n). , , (P0, P1) 0 (P1, P2) 1 (P2, P3) 2 ..
x : x, * , dn - P (n-1) Pn),
---*----------*------*--------*---------....--------*---
^ ^ ^ ^ ^
P0 (d0) P1 (d1) P2 (d2) P3 (d3) .... d(n) Pn
O (n). .
:
(1 * (n - 1) * Distances[0]) +
(2 * (n - 2) * Distances[1]) +
(3 * (n - 3) * Distances[2]) +
.
.
.
(1 * (n - 1) * Distances[n-1])
P0. P0 P1 Pn
= d(P0, P1) + d(P0, P2) + ... + d(P0, Pn)
= d[0] + (d[0] + d[1]) + ... + (d[0] + d[1] till d[n-1])
= (n-1)*d[0] + (n-2)*d[1] + ... + (n-1)*d[n-1]
In the same way, we take P1 and calculate its distance from P2 to Pn
Then take P3 ... until the final consideration of only the distance between P (n-1) and Pn
When summing these distances, we directly get the formula indicated above.
Therefore, if the points are set sorted , the runtime is O (n), and if the points are set unsorted , the runtime is O (maxX - minX), which is still growing linearly.