答案 0 :(得分:2)
对于最大距离,您的解决方案是正确的。没有更好的解决方案,因为必须遍历数组中的所有元素。时间复杂度为SELECT u.user_id, u.fried_id
FROM (SELECT user_id, friend_id
FROM friendship
WHERE user_id < friend_id AND status = 'done') u
JOIN (SELECT user_id, friend_id
FROM friendship
WHERE user_id > friend_id AND status = 'done') f ON
u.user_id = f.friend_id AND
u.friend_id = f.user_id
。
伪码:
O(n)
您问题中的伪代码用于查找数组中任何对之间的最小距离。更有效的解决方案是:
MaxDistance(A)
min = max = A[0]
for i=1 to n-1
if A[i] < min
min = A[i]
if A[i] > max
max = A[i]
return (max-min)
进行排序。 A
O(nlogn)
伪码:
O(n)
总时间复杂度:MinDistance(A)
sort(A)
min_dist = infinity
for i=1 to n-1
dist = A[i]-A[i-1]
if (min_dist > dist)
min_dist = dist
return min_dist