[leetcode-排序]--75. Sort Colors

来源:互联网 发布:油汀电热膜哪个好 知乎 编辑:程序博客网 时间:2024/04/30 10:35

Question 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?

中文:有一个数组由n个颜色对象组成,在、颜色对象分别是红、白、蓝。将他们排序,使得数组中颜色顺序是红、白、蓝。现在分别用0、1、2来表示红白蓝。 不得使用库函数的排序方法,

对于两轮遍历来说比较简单,一轮遍历直接收集0和1和2的个数,然后第二轮遍历直接根据个数赋值,这是非常简单的做法。那么能不能通过一轮遍历实现呢?

解决思路:

(1)两轮遍历解决

思路简单,第一轮收集0,1,2个数,第二轮赋值。

/** * 两轮遍历 * @param nums */public static void sortColors1(int[] nums) {    int num0, num1, num2;    num0 = num1 = num2 = 0;    for (int i = 0; i < nums.length; i++) {        if (nums[i] == 0)            num0++;        else if (nums[i] == 1)            num1++;        else if (nums[i] == 2)            num2++;    }    int i=0;    while (num0>0){        nums[i++]=0;        num0--;    }    while (num1>0){        nums[i++]=1;        num1--;    }    while (num2>0){        nums[i++]=2;        num2--;    }}

(2)一轮遍历解决

一轮遍历: 使用了两个索引 :indexred 表示红色(0)的索;indexblue( ) 表示蓝色的索引。这两个索引分别从首尾向中间夹逼;
用i来从前往后遍历( 注意,这里遍历的为边界是indexblue索引,而不是nums.lengtjh-1,只需要遍历到indexblue, indexblue后面的就全部是2了。此外遍历到nums.lengtjh-1可能会出现indexblue前面是1了而indexblue后面的2与前面的1交换,出现错误。 ), 如果碰到0 就和indexred交换; 如果碰到2 就和indexblue交换。

实现源码:

public static void sortColors2(int[] nums) {    int indexred = 0;    int indexblue = nums.length-1;    int temp;    for (int i=0; i<=indexblue; i++){        //只要nums[i]为2 就执行交换, 防止2,1,2 这种情况,这种情况下会不被排序        while (nums[i] == 2 && i<indexblue){            //将nums[i] 与 nums[indexblue] 交换            temp = nums[i];            nums[i] = nums[indexblue];            nums[indexblue] = temp;            indexblue--;        }        while(nums[i] == 0 && i>indexred){            //将nums[i] 与 nums[indexred] 交换            temp = nums[i];            nums[i] = nums[indexred];            nums[indexred] = temp;            indexred++;        }    }}

本文的完整代码 github 地址:
https://github.com/leetcode-hust/leetcode/blob/master/louyuting/src/leetcode/Question75.java

0 0
原创粉丝点击