Given an array withnobjects 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.
tag: two pointers
class Solution {
public void sortColors(int[] nums) {
int n = nums.length;
int index0 = 0, index2 = n - 1, index1 = 0;
while (index1 <= index2){
if (nums[index1] == 2){
swap(nums, index1, index2--);
}
else if (nums[index1] == 0){
//这个时候index0只有可能是1
swap(nums, index0++, index1++);
}
else{
index1++;
}
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}