俊介三

一天更新一点,一天积累一点

导航

Sort Color

Posted on 2013-03-11 20:06  俊介三在前进  阅读(144)  评论(0)    收藏  举报

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.

http://discuss.leetcode.com/questions/251/sort-colors

不能再额外开变量,记录0,1,2的个数,再填充它。。就是说要遍历一遍,把相应的数换一下以排序。

有人写这样的代码:

void sortColors(int A[], int n) {
        int p0 = 0, p2 = n;
        for (int i = 0; i < p2; ++i) {//p2在循环体中改变了它的值
            //这样写让人费解
            // put zeros at the beginning
            if (A[i] == 0) {
                swap(A[i], A[p0++]);
            }
            // put twos at the end
            else if (A[i] == 2) {
                swap(A[i--], A[--p2]);
            }
        }
    }

还有这样的:

void sortColors(int A[], int n) {
        int w = 0, b = 0; //012顺序为R W B
        for (int i = 0; i < n; ++i) {
            if (A[i] == 0) {
                swap(A[b], A[i]);
                swap(A[b++], A[w++]);
            } else if (A[i] == 1) {
                swap(A[b++], A[i]);
            }
        }
    }