Monday, May 12, 2014

[LeetCode] Sort Colors

Problem Statement (link):
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?
Analysis:
As the problem Follow-up suggested, we could use counting sort to solve this problem, it's implemented in Sol 1 below.

However, to solve this problem in one pass, we need to think otherwise. Actually, this problem is called "Dutch flag problem". The thought is to have three parameters indicating the boundaries, and as we scan through the entire array, we keep swapping entries.

Code:
Sol 1 - counting sort:
class Solution {
public:
    void sortColors(int A[], int n) {
        int r = 0; int w = 0; int b = 0;

        // pass 1 - count
        for(int k = 0; k < n; k++) {
            if (A[k] == 0)  r++;
            else if (A[k] == 1) w++;
            else if (A[k] == 2) b++;
        }

        // pass 2 - assign values
        for (int k = 0; k < n; k++) {
            if (k < r)  A[k] = 0;
            else if (k < r + w && k >= r)   A[k] = 1;
            else if (k >= r + w) A[k] = 2;
        }
    }
};


Sol 2 - Dutch flag problem algorithm:
class Solution {
public:
    void sortColors(int A[], int n) {
        int low=0;
        int mid=0;
        int high=n-1;

        while(mid<=high) {
            if (A[mid]==0) swap(A,low++,mid++);
            else if (A[mid]==1) mid++;
            else if (A[mid]==2) swap(A,mid,high--);
        }
    }
    void swap(int A[], int a, int b) {
        int tmp=A[a];
        A[a]=A[b];
        A[b]=tmp;
    }
};

No comments:

Post a Comment