Resizable Array and Amortized Runtime

前端 未结 4 2066
無奈伤痛
無奈伤痛 2020-12-22 06:36

\"Therefore, inserting N elements takes O(N) work total. Each insertion is O(1) on average, each though some insertions take O(N) time in the worst case.\" This quote is fou

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-22 07:20

    I think you'd better understand above statement like this way.

    At first. an array size is just 1. and insert it one element. Now the array is full!. you have to resize it as much as 2 times of the previous one.

    Next, the array size is 2. Let this process progress. You can easily notice that the moment you have to resize an array is 1, 2, 4, 8, 16, 32, ... , 2^r.

    I will give you questions.

    1. How many times are the moments you have to resize an array?
    2. How much the total cost until N(N>=0) steps?

    1st answer is floor(lgN) times. you can figure it out easily I think. If you find the first answer, calculating the total cost of this N steps which is the second answer is pretty easy.(I don't know how I can express mathematical symbol:<)

    1 + 2 + 4 + 8 + 16 + ... + 2^(floor(lgN)) = 2^(floor(lgN)+1) - 1 => O(n)

    To get the average cost of each step, divide total cost into N => O(1)

    I think worst case the reference mentions is when the array is needed to be resized. The cost of this readjustment is in proportional to the number of elements are in the array, O(N)

提交回复
热议问题