[leetcode] 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.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

Could you come up with an one-pass algorithm using only constant space?

因为只有0,1,2三个数来排序,并且只允许one-pass的时间。所以考虑用多个指针来标记已经访问过的数组的装填。

oneStart表示排序后1开始的位置,twoStart表示排序后2开始的位置。0从0处开始,2到i处结束。

需要注意没有2或没有1或没有0的情况,也即oneStart>twoStart || twoStart > i的情况,单独分析。

class Solution {
public:
    void sortColors(int A[], int n) {
        int i = 0;
        int oneStart = 0;
        int twoStart = 0;
        while(i < n){
            if(A[i] == 0){
               A[oneStart++] = 0;
               if(oneStart > twoStart){
                   twoStart++;
               }else{
                   A[twoStart++] = 1;
               }
               if(twoStart > i){
                   ;
               }
               else{
                   A[i] = 2;
               }
            }
            else if(A[i] == 1){
                A[twoStart++] = 1;
                if(twoStart > i){
                    ;
                }
                else{
                    A[i] = 2;
                }
            }
            i++;
        }
    }
};

 

Untitled

 

An quick sort approach

class Solution {
public:
    void sortColors(vector<int>& nums) {
        _qsort(nums, 0, nums.size() - 1);
    }
    //Both nums[start] and nums[end] are availiable
    void _qsort(vector<int>& nums, int start, int end){
        if(start >= end) return;
        int pivot = median(nums, start, end);
        int i = start;
        int j = end - 1;
        while(i < j){
            while(nums[++i] < pivot)
                ;
            while(nums[--j] > pivot)
                ;
            if(i < j){
                swap(nums[i], nums[j]);
            }
        }
        swap(nums[end - 1], nums[i]);
        _qsort(nums, start, i - 1);
        _qsort(nums, i + 1, end);
    }
    int median(vector<int>& nums, int start, int end){
        int mid = (start + end) / 2;
        if(nums[start] > nums[mid]){
            swap(nums[start], nums[mid]);
        }
        if(nums[mid] > nums[end]){
            swap(nums[mid], nums[end]);
        }
        if(nums[start] > nums[mid]){
            swap(nums[start], nums[mid]);
        }
        swap(nums[mid], nums[end - 1]);
        return nums[end - 1];
    }
};

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.