Efficiently get sorted sums of a sorted list

后端 未结 8 2195
小蘑菇
小蘑菇 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:16

    This question has been wracking my brain for about a day now. Awesome.

    Anyways, you can't get away from the n^2 nature of it easily, but you can do slightly better with the merge since you can bound the range to insert each element in.

    If you look at all the lists you generate, they have the following form:

    (a[i], a[j]) | j>=i

    If you flip it 90 degrees, you get:

    (a[i], a[j]) | i<=j

    Now, the merge process should be taking two lists i and i+1 (which correspond to lists where the first member is always a[i] and a[i+1]), you can bound the range to insert element (a[i + 1], a[j]) into list i by the location of (a[i], a[j]) and the location of (a[i + 1], a[j + 1]).

    This means that you should merge in reverse in terms of j. I don't know (yet) if you can leverage this across j as well, but it seems possible.

提交回复
热议问题