给定一个包含红,白,蓝且长度为 n 的数组,将数组元素进行分类使相同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数 0,1 和 2 分别代表红,白,蓝。
样例
给你数组 [1, 0, 1, 2]
, 需要将该数组原地排序为 [0, 1, 1, 2]
。
挑战
一个相当直接的解决方案是使用计数排序扫描2遍的算法。
首先,迭代数组计算 0,1,2 出现的次数,然后依次用 0,1,2 出现的次数去覆盖数组。
你否能想出一个仅使用常数级额外空间复杂度且只扫描遍历一遍数组的算法?
解题思路1:
由于要排序的元素类型只有0,1,2三种,所以使用计数排序,遍历一遍数组,统计出0,1,2出现的次数,然后将统计次数的结果再赋值回原数组即可。
public class Solution {
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
public void sortColors(int[] nums) {
// write your code here
int[] times = new int[3];
for(int i=0; i<nums.length; i++)
times[nums[i]]++;
int index=0;
for(int i=0; i<3; i++)
for(int j=0; j<times[i]; j++)
nums[index++] = i;
}
}
解题思路2:
但是思路1中遍历了两遍数组,接下来利用快排中partition操作,将数组分为左中右三块,分别为0,1,2,设立几个指针来维护这三块的性质,只需遍历一次就得到结果。如下图所示:
若i指向的e==1,直接i++即可。
若i指向的e==2,交换*i与*(two-1),然后two--
若i指向的e==0,交换*i与*(zero+1),然后zero++, i++
class Solution {
public void sortColors(int[] nums) {
int zero = -1, i = 0, two = nums.length;
while(i < two){
if(nums[i] == 1)
i++;
else if(nums[i] == 0)
swap(nums, i++, ++zero);
else
swap(nums, i, --two);
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}