数组——sort colors

来源:互联网 发布:平板电脑装ubuntu 编辑:程序博客网 时间:2024/06/05 05:29

题意:对一个容量为n含有红色(用0表示),白色(用1表示),和蓝色(用2表示)的数组按升序排序。。。

 public void sortColors(int[] A) {        if(A == null||A.length == 0)            return;        //计数排序;        int red=0;int white=0;int blue=0;        for(int i=0;i<A.length;i++)          {            if(A[i] == 0)              { red++; }            else if(A[i] == 1)              { white++; }            else              { blue++; }           }        for(int i=0;i<A.length;i++)           {            if(red>0)               {                A[i]=0;                red--;}            else if(white>0)               {                A[i]=1;                white--;}            else               {                A[i]=2;                blue--; }           }    }




0 0
原创粉丝点击