Sort Colors

LeetCode #75


Description:

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.

Example:

Note

Idea:

也叫Dutch flag problem。

类似partition in quickSort.

Code:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        // i for 0, j for 1, k for 2
        int i=-1;
        int j=0;
        int k=nums.size();

        while(j<k){
            if(nums[j]==1) j++;
            else if(nums[j]==0){
                swap(nums[j], nums[++i]);
                j++;
            }
            else if(nums[j]==2){
                swap(nums[j], nums[--k]); // 这时候不用j++
            }
        }

    }
};

results matching ""

    No results matching ""