How to implement three stacks using a single array

后端 未结 17 802
情书的邮戳
情书的邮戳 2020-12-23 15:10

I came across this problem in an interview website. The problem asks for efficiently implement three stacks in a single array, such that no stack overflows until there is no

17条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 15:51

    Split array in any 3 parts (no matter if you'll split it sequentially or interleaved). If one stack grows greater than 1/3 of array you start filling ends of rest two stacks from the end.

    aaa bbb ccc
    1   2   3
    145 2   3
    145 2 6 3
    145 2 6 3 7
    145 286 3 7
    145 286 397
    

    The worse case is when two stacks grows up to 1/3 boundary and then you have 30% of space waste.

提交回复
热议问题