LeetCode题解:Sort Colors

Sort Colors

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.

思路:

一个可行的办法是,首先遍历一下数组,分别计算其中0,1,2的个数,然后再次遍历数组,按照0,1,2的个数再分别填回。这样时间复杂度是O(2n)。

题目中希望能够一次遍历数组就解决这个问题。这样就得考虑利用数组里只有三种不同的值的情况。采用一个类似快速排序的方法。

首先设定两个指针。第一个指针last0,在指针及其左边的数字都是0。第二个指针first2,在指针及其右边的数字都是2。

现在用一个指针i遍历last0和first2之间的数字。如果这个数字是2,则让first2左移一位,交换first2和i指向的值,同时重新检查i的值。如果这个数字是0,则让last0右移一位。这时有两种情况。第一种情况,last0和i重合,那么直接检查下一个数字即可。反之,右移后的last0必然指向的值是1,将last0和i交换。

这样,在循环过程中,last0及其左边的数字必然是0,last0和i之间的数字如果有的话必然是1,first2及其右边的数字必然是2。在i和last0重合的时候,排序完成。

题解:

class Solution {
public:
    void sortColors(int A[], int n) {
        if (n == 0)
            return;
    
        int last0 = 0;
        while(A[last0] == 0) ++last0;
        last0--;    // jump back to 0
    
        int first2 = n-1;
        while(A[first2] == 2) --first2;
        first2++;   // jump forward to 2
    
        int i = last0 + 1;
        while(i < first2)
            if (A[i] == 2 )
                swap(A[i], A[--first2]);
            else if (A[i] == 0)
                swap(A[i++], A[++last0]);
            else
                ++i;
    }
};


你可能感兴趣的:(LeetCode)