LeetCode: Sorted Color

Title:

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.

直观的解法是使用计数排序

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int *c = new int [3];
        memset(c,0,sizeof(int)*3);
        for (int i = 0; i < nums.size(); i++){
            c[nums[i]]++;
        }
        nums.clear();
        for (int i = 0 ; i < 3; i++){
            for (int j = 0 ; j < c[i]; j++){
                nums.push_back(i);
            }
        }
    }
};

也可以遍历一次就能得到结果,使用3个下标,分别指向0,1,2对应的下标位置。可以这么理解,最左边是0,最右边是2,中间遇到1不用管

class Solution {
public:
    void sortColors(int A[], int n) {
        if(n <= 1) return;
        int start = -1, end = n;
        int p = 0;
        while(p < n && start < end){
            if(A[p] == 0){
                if(p > start) swap(A, ++start, p);
            }else if(A[p] == 2){
                if(p < end) swap(A, p, --end);
            }else ++p;
        }
    }
private:
    void swap(int A[], int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
};
原文地址:https://www.cnblogs.com/yxzfscg/p/4475382.html