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.

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

http://www.lintcode.com/en/problem/sort-colors/

Discussion


由于0, 1, 2 非常紧凑,首先想到计数排序(counting sort),但需要扫描两遍,不符合题目要求。
由于只有三种颜色,可以设置两个index,一个是red 的index,一个是blue 的index,两边往中 间走。时间复杂度O(n),空间复杂度O(1)。

Solution

class Solution{
public:
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */    
    void sortColors(vector<int> &nums) {
        // write your code here
        int n = nums.size();
        int red = 0; 
        int blue = n-1;
        for(int i=0; i<blue+1;) {
            if(nums[i] == 0) {
                swap(nums[i++], nums[red++]);
            } else if (nums[i] == 2) {
                swap(nums[i], nums[blue--]);
            } else 
                i++;
        }
    }
};

results matching ""

    No results matching ""