Mauritus national flag problem

前端 未结 6 761
时光说笑
时光说笑 2021-02-14 16:52

I\'ve made a solution for the Dutch national flag problem already.

But this time, I want to try something more difficult: the Mauritus national flag problem - 4 colours,

6条回答
  •  星月不相逢
    2021-02-14 17:33

    This is just like the Dutch national flag problem, but we have four colors. Essentially the same strategy applies. Assume we have (where ^ represents the point being scanned).

      RRRRBBB???????????YYYYGGGG
             ^
    

    and we scan a

    1. red, then we swap the first blue with the current node
    2. BLUE we do nothing
    3. yellow we swap with the last ?
    4. Green we swap the last yellow with the last ? Then the current node with the swapped ?

    So we need to keep track or one more pointer than usual.

    We need to keep track of the first blue, the first ?, the last ?, the last Y

    In general, the same strategy works for any number of colors, but an increasing numbers of swaps are needed.

提交回复
热议问题