Efficiently get sorted sums of a sorted list

后端 未结 8 2197
小蘑菇
小蘑菇 2021-02-18 16:50

You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in

相关标签:
8条回答
  • 2021-02-18 17:25

    No matter what you do, without additional constraints on the input values, you cannot do better than O(n^2), simply because you have to iterate through all pairs of numbers. The iteration will dominate sorting (which you can do in O(n log n) or faster).

    0 讨论(0)
  • 2021-02-18 17:37

    You can do this in two lines in python with

    allSums = set(a+b for a in X for b in X)
    allSums = sorted(allSums)
    

    The cost of this is n^2 (maybe an extra log factor for the set?) for the iteration and s * log(s) for the sorting where s is the size of the set.

    The size of the set could be as big as n*(n-1)/2 for example if X = [1,2,4,...,2^n]. So if you want to generate this list it will take at least n^2/2 in the worst case since this is the size of the output.

    However if you want to select the first k elements of the result you can do this in O(kn) using a selection algorithm for sorted X+Y matrices by Frederickson and Johnson (see here for gory details). Although this can probably be modified to generate them online by reusing computation and get an efficient generator for this set.

    @deuseldorf, Peter There is some confusion about (n!) I seriously doubt deuseldorf meant "n factorial" but simply "n, (very excited)!"

    0 讨论(0)
提交回复
热议问题