三色旗问题中的快排应用

来源:互联网 发布:淘宝冷门暴利产品 编辑:程序博客网 时间:2024/09/21 08:50
今天在看三色旗问题的时候觉得这个问题用的就是快排思想,然后查了一下,Letcode上正好有这样类似的一道题目下面是Letcod上面的这个问题的题目75.Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.Note:You are not suppose to use the library's sort function for this problem. 就是说,一个绳子上面blue,red,white,三种颜色开始时随机排布,然后让你把他们变成按照顺序的blue,white,red,这种问题当然可以直接用循环来完成,不过既然单独的弄成一道题目那就没那么简单直接了,首先,如果我们直接用循环(记下几个红几个蓝几个白,然后重新赋值就好)来完成,但是这样要遍历两次,有没有更快的呢?所以我们就会想到快排,那么到底是如何利用快排的思想呢?首先要知道什么是快排的思想,快排就是通过分治来实现排序,先找一个基数,比它大的放右边,比它小的放左边,然后就是分成两个区域了,这两个区域里面再这样操作,直到各区域只有一个数就停止。那么这个里面呢?我觉得题目已经有一些暗示性了,通过数字的比较,1就是中间的那个数字,比1大的放右边,比1小的放左边就好了。利用三个指针,第一个指向1的开始,第二个指向1的末尾,第三个开始遍历数组,将整个区域分为四个部分,B,W,R然后W与R区域中间的就是未处理区(用N表示),第三个指针就是不停的对N区域处理,如果遇到0,就把它与1开头的指针指向的1交换,然后B++,W++,遇到2就是与第二个指针指向的2交换,然后R--,直到第三个指针与第二个指针指向相同具体代码:
public class Solution {    public void sortColors(int[] A) {        //Implement counting sort        int count1 = 0;         int count2 = 0;         int count0 = 0;        for(int i = 0; i < A.length; i++){            if(A[i] == 2){                count2++;            } else if(A[i] == 1){                count1++;                swap(A, i , i-count2);            } else {                count0++;                swap(A, i, i-count2);                swap(A, i-count2, i-count2-count1);            }        }    }    public void swap(int[] A, int i, int j){        int temp;        temp = A[i];        A[i] = A[j];        A[j] = temp;    }}

当然,这题还有其他解法,大家可以参考这里http://www.cnblogs.com/felixfang/p/3680047.html
还有更加详细的解法说明,大家可以看这里http://blog.csdn.net/JeamKing/article/details/44408383

1 0