LeetCode 之 Sort Colors — C 实现

来源:互联网 发布:淘宝店铺注册单安全吗 编辑:程序博客网 时间:2024/05/14 13:48

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.

给定一个含有 n 个对象的数组,对象可能为红、白、蓝三种颜色,调整这些对象使其按照红、白、蓝的顺序排列。

这里我们分别用0,1,2 代表红、白、蓝三种颜色。

说明:不能使用库排序函数。

分析:

使用两个游标 left 和 right,left 左边为 0,right 右边为 2,它们中间为 1。

从数组开头开始扫描,遇见0就将其换到 left 左边,此处设为1,遇到1不处理继续查找,遇到 2,从数组尾部开始扫描直到找到不是 2的数字,将其对换但不改变此处的位置等待下个循环处理,只需要改变从数组后面向前扫描的指针,直到前后扫描的下标重合为止。

void sortColors(int* nums, int numsSize) {    int left = 0, right = numsSize - 1;/*left指向1的位置,左边是0,right右边是2,中间是1*/    int low = 0, high = numsSize - 1;        if(!nums || numsSize == 0) /*空*/    {        return;    }        while(low <= high)    {        if(nums[low] == 0)        {            if(low > left)/* 0前面有1 */            {                nums[left++] = 0;                nums[low] = 1;                while(left < low && nums[left] == 0)/* left移到第一个为1或者low的位置*/                {                    ++left;                }                ++low; /*移到下一个数*/            }            else            {                ++low;                ++left;            }        }        else if(nums[low] == 1)        {            ++low;        }        else        {            while(low < high && nums[high] == 2)/*找第一个不是2的数*/            {                --high;            }            nums[low] = nums[high]; /*将此处的值放入前面为2的位置*/            nums[high--] = 2;        }    }}

0 0