Sort Colors 颜色排序(只有3类值的排序)

来源:互联网 发布:java互联网面试题 编辑:程序博客网 时间:2024/06/05 10:09

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.

---------------------------------------------------------------------------------------------------------------------------------------------------------


这个问题实质上就是对于0, 1, 2的序列进行排序。由于只有3类值。

我们可以实现一个时间复杂度为 O ( n ) , 空间复杂度为 O ( 1 )的算法。

核心的思想是:

将0 的全都放到left边, 将2 的全都放到right边,

最后,就是排好序的了。

为了实现这个思想,

我们需要有一个left 指针,和一个right指针。

让left指针前面的都是0, right指针后面的都是1。

同时一个cur指针,从左到右遍历这个数组。

1. cur 遍历到0的时候,我们将0 与 left 指向的值互换。left++;

2. 当cur遍历到2的时候,我们将2 与right指向的值互换,right--;

3. 当cur遍历到1的时候,cur++, 不用管,继续往下走。

4. 注意:如果0已经放在符合要求的位置了,left++, cur++

               如果2已经放在符合要求的位置了,说明后面的都是2了,可以结束了。


运行时间:



代码:

    public void sortColors(int[] nums) {        if (nums == null || nums.length == 0 || nums.length == 1) {            return;        }        int left = 0;        int right = nums.length - 1;        int cur = left;        while (cur <= right) {            if (nums[cur] == 0) {                if (cur == left) {// already on the right place                    cur++;                    left++;                } else {                    nums[cur] = nums[left];// swap                    nums[left] = 0;                    left++;                }            } else if (nums[cur] == 1) {                cur++;            } else if (nums[cur] == 2) {                if (cur == right) {// already on the right place, can return                     return;                }                nums[cur] = nums[right];                nums[right] = 2;// swap                right--;            }        }    }


2 0
原创粉丝点击