75. 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?

partition

类似于快速排序的思想
以 1 为pivot 一次排序即可
遇到 1 不管
遇到 0 放在 l 指针处
遇到 2 放在 r 指针处

void sortColors(vector<int>& nums) {
    int l = 0, r = nums.size() -1 ;
    int i = 0;
    while(i <= r){
        if(nums[i] == 0){
            if(i > l) swap(nums[i], nums[l++]);
            else i++;
        }else if(nums[i] == 2){
            if(i < r) swap(nums[i], nums[r--]);
            else break;            
        }else
            i++;
    }
}

冒泡排序

直接用排序算法

void sortColors(vector<int>& nums) {
    for(int k = 1; k < nums.size(); k++){
        for(int i = 0; i < nums.size() - k;i++){
            if(nums[i] > nums[i + 1]) 
                swap(nums[i], nums[i + 1]);
        }
    }
}

你可能感兴趣的:(75. Sort Colors)