Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

algorithm - Finding sum of Absolute Difference of Every pair of integer from an array

Given an array, find the sum of the absolute difference of every pair of integers.

For example: Given a[]= {2,3, 5, 7 };

output would be (3-2) + (5-2) + (7-2) + (5-3) + (7-3) + (7-5) = 17.

It must be done better than O(n^2).

The original array isn't necessarily sorted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

note you add each number exactly k times (where k is its place if you sort the list)
also, you subtract each number exactly n-1-k times
you can sort the list (O(nlogn)) and then iterate over the sorted array, multiplying each element as mentioned above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...