075_Sort_Colors

Sort Colors

Difficulty Medium

tags partition

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?

思路

这是一个three partition 问题:

  1. 和quick sort的partition相同的是,都有左右两个指针lo, hi. 而且lo, hi的作用基本相同
    [0, lo) 范围内的数值都小于(quick sort时可以等于)v, (hi, nums.size()-1]范围内的数值都大于(quick sort时可以等于)v
  2. 不同的是,quick sort的partition中[0, lo), (hi, nums.size()-1]中可以包含等于v的值,而这里不包含。
    即quick sort的partition只需要有 <=, > 两种判别,而这里的partition中需要有<, ==, >三种判别。
    两种判别的情况下,不需要中央游标i就可以搞定(见附录) 而三种判别的情况下,我们需要引入中央游标i。

一种quick sort中的partition中即实现了此三分排序

static int partition(vector<int>& a, int lo, int hi) {
    int i = lo;
    int j = hi + 1;
    int v = a[lo];
    while (true) { 
        // find item on lo to swap
        while (a[++i] < v)
            if (i == hi) break;

        // find item on hi to swap
        while (v < a[--j])
            if (j == lo) break;      // redundant since a[lo] acts as sentinel

        // check if pointers cross
        if (i >= j) break;

        swap(a[i], a[j]);
    }

    // put partitioning item v at a[j]
    swap(a[lo], a[j]);

    // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
    return j;
}

solution 1

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int lo = 0, hi = nums.size()-1, i = 0;
        int v = 1;
        while (i<=hi) { 
            if (nums[i] > v) 
                swap(nums[i], nums[hi--]);
            else if (nums[i] < v) 
                swap(nums[i++], nums[lo++]);
            else 
                i++;
        }
    }
};
posted @ 2017-12-13 15:45  whensean  阅读(142)  评论(0)    收藏  举报