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?
题意:数组排序。不能使用提供的排序算法,我们的第一想法是计算0,1,2的数目,然后对数组元素重新赋值即可。
代码:
class Solution {
public void sortColors(int[] nums) {
if(nums.length == 0)
return;
int red = 0;
int white = 0;
int blue = 0;
for(int i : nums){
if(i == 0)
red++;
if(i == 1)
white++;
else
blue++;
}
int i = 0;
while(i<red)
nums[i++] = 0;
while(i<red+white)
nums[i++] = 1;
while(i<nums.length)
nums[i++] = 2;
}
}
我们使用2个指针,分别指向数组中出现的第一个1和第一个2,
当我们遇到0时,判断前方是否存在1,若存在,交换,更新指针;若不存在,继续判断前方是否存在2,若存在,交换,更新指针
当我们遇到1时,判断是否需要更新指针,判断前方是否存在2,若存在,交换,更新指针
当我们遇到2时,判断是否需要更新指针.
下面是代码:
class Solution {
public void sortColors(int[] nums) {
int index1 = nums.length; //index1表示数组中第一个1的位置
int index2 = nums.length; //index2表示数组中第一个2的位置
for(int i=0;i<nums.length;i++){
if(nums[i]==0){
if(i>index1){ //0元素与前方第一个1交换
swap(nums,i,index1);
if(nums[index1+1]==2){
swap(nums,index1+1,i);
index2++;
}
index1++;
}else{ //0元素与前方第一个2交换
if(i>index2){
swap(nums,index2,i);
index2++;
}
}
}
if(nums[i]==1){
if(i<index1)
index1 = i;
if(i>index2){
swap(nums,i,index2);
index1 = Math.min(index1,index2);
index2++;
}
}
if(nums[i]==2)
if(i<index2)
index2 = i;
}
}
public void swap(int[] nums,int a,int b){
int c = nums[a];
nums[a] = nums[b];
nums[b] = c;
}
}