Efficiently get sorted sums of a sorted list

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

    Edit as of 2018: You should probably stop reading this. (But I can't delete it as it is accepted.)

    If you write out the sums like this:

    1 4  5  6  8  9
    ---------------
    2 5  6  7  9 10
      8  9 10 12 13
        10 11 13 14
           12 14 15
              16 17
                 18
    

    You'll notice that since M[i,j] <= M[i,j+1] and M[i,j] <= M[i+1,j], then you only need to examine the top left "corners" and choose the lowest one.

    e.g.

    • only 1 top left corner, pick 2
    • only 1, pick 5
    • 6 or 8, pick 6
    • 7 or 8, pick 7
    • 9 or 8, pick 8
    • 9 or 9, pick both :)
    • 10 or 10 or 10, pick all
    • 12 or 11, pick 11
    • 12 or 12, pick both
    • 13 or 13, pick both
    • 14 or 14, pick both
    • 15 or 16, pick 15
    • only 1, pick 16
    • only 1, pick 17
    • only 1, pick 18

    Of course, when you have lots of top left corners then this solution devolves.

    I'm pretty sure this problem is Ω(n²), because you have to calculate the sums for each M[i,j] -- unless someone has a better algorithm for the summation :)

提交回复
热议问题