Amortized Time with Hash Table

六月ゝ 毕业季﹏ 提交于 2021-01-07 03:04:23

问题


I solved the first part of the question but stuck at the second part.

I have an elevator and want to support the following:

Init() Set the elevator to start from floor 0 and its travel direction to be up (This function is called only once and the direction can't be changed). O(1)

AddStop(K) save into the DS that elevator should stop when it reaches floor k. O(log n) while n is the total number of stops for the elevator.

NextStop() send the elevator to its next stop position, if it's in the final available stop location then the elevator stays at its current place. O(1).


My Solution: I used AVL trees such that each node has a pointer to the node that comes exactly after it and the node before it (According to floor number)

When I add new floor I change its 2 pointers accordingly and change the pointers to the effected node in the tree.

Part 2:

It's known that after i calls for AddStop(K) then the highest floor the elevator could stop at is maximum 2i.

New Complexity Time requirements:

Init() - O(1). (Didn't change)

AddStop(K) - O(1). Amortized with NextStop()

NextStop() - O(1). Amortized with AddStop(K)

Can someone help me solve part 2?


Update:

I think part 1 isn't relevant for solving part 2, Plus I highly believe we should use Hash Tables here.


回答1:


The important thing is this condition:

after i calls for AddStop(K) then the highest floor the elevator could stop at is maximum 2i

That means that at worst you're stopping at half the floors, so it's not very wasteful to have an array indexed by floor number, storing a boolean to say whether to stop.

For NextStop() simply iterate from the current floor position until you find the next floor to stop at.

To keep the complexity to amortised O(1), whenever AddStop needs a bigger array, it's enough to resize the array to double its previous size. That way, say you end up with a X floors, 0 to half of them will have been added directly since the last resize, half to 1/4 will have had to be copied once as you resized, 1/4 to 1/8 will have been copied twice, 1/8 to 1/16 copied thrice etc. - at worst the number of copies is 1 + 2/2 + 3/4 + 4/8 + 5/16 etc. - it's a limiting sum that Nicole Oresme's theorem says levels out at 4 - a constant factor so still O(1) amortised.

No hash tables involved.



来源:https://stackoverflow.com/questions/65448315/amortized-time-with-hash-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!