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.
思路:
这道题目给了我们一个颜色的array,让我们sort一下,按照0,1,2的顺序。根据题目要求,我们只能遍历array一次,可以用到two pointers来实现。设一个指针red 在开头,blue 在最后。想法就是,遇到红色0,就交换,把0放到最左边去;遇到蓝色2就交换,把2都放到最右边去,这样1就会被保留在最中间。需要注意的是,当把蓝色2交换完毕之后,需要i–, 停留 i 在原地一次,因为还需要继续检查 被2交换回来的数字。那当遇到红色0,交换完毕不需要停留i 的原因是, 交换回来的只可能是1,对于1,我们不需要做任何处理,直接过就可以。
class Solution {
public void sortColors(int[] nums) {
int red = 0;
int blue = nums.length-1;
for(int i=0; i<=blue; i++)
{
if(nums[i] == 0) // if find 0, swap with red pointer
{
int temp = nums[i];
nums[i] = nums[red];
nums[red] = temp;
red++;
}
else if(nums[i] == 2) // if find 2, swap with blue pointer
{
int temp = nums[i];
nums[i] = nums[blue];
nums[blue] = temp;
i--;
blue--;
}
}
}
}
class Solution {
public void sortColors(int[] nums) {
int numZero = 0;
int numOne = 0;
int numTwo = 0;
for(int i : nums) {
if(i == 0) numZero++;
if(i == 1) numOne++;
if(i == 2) numTwo++;
}
for(int i = 0; i < nums.length; i++) {
if(numZero != 0) {
nums[i] = 0;
numZero--;
} else if(numOne != 0) {
nums[i] = 1;
numOne--;
} else if(numTwo != 0) {
nums[i] = 2;
numTwo--;
}
}
}
}