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.
Notice
You are not suppose to use the library's sort function for this problem.
You should do it in-place (sort numbers in the original array).
这题用counting sort可以做,但是会遍历两遍数组,第一次把0,1,2数量记下来,第二遍把数字填上去。
也可以用insertion sort。
这里我用了三个pointer,left负责追踪0的插入位置,right负责追踪2的插入位置,i是当前遍历数字的index。
然后当前数字是0,或2就交换,然后更新left,right,i
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
if(nums.length == 0){
return ;
}
int left = 0;
int right = nums.length-1;
int i = 0;
while( i <= right) {
if(nums[i] == 2){
nums[i] = nums[right];
nums[right] = 2;
right--;
}else if (nums[i] == 0){
nums[i] = nums[left];
nums[left] = 0;
left++;
i++;
}else{
i++;
}
}
}
}