Mauritus national flag problem

前端 未结 6 770
时光说笑
时光说笑 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:17

    Basically, maintain the following :

    a[0-p] => '0'
    a[p-q] => '1'
    a[q-r] => '2'
    a[r-s] => traversing! 
    a[s-length] => '3'          
    

    Code:

            int p=-1,q=-1,r=0,s=a.length-1;
            while(r<=s){
                if(a[r]==0){
                    exchange(a,p+1,r);
                    p++;r++;
                    if(q!=-1)
                        q++;
                } else if (a[r]==1){
                    if(q==-1)
                        q=p;
                    exchange(a,q+1,r);
                    q++;r++;
                } else if(a[r]==2) {
                    r++;
                } else {
                    exchange(a,r,s);
                    s--;
                }
    
            }
    

提交回复
热议问题