Sort Colors
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.
Solution1:
public void sortColors(int[] nums) {
int begin = 0;
int end = nums.length - 1;
int i = 0;
while (begin < end && i <= end) {
if (nums[i] == 0) {
swap(nums, i, begin);
begin++;
i++;
} else if (nums[i] == 2) {
swap(nums, i, end);
end--;
} else {
i++;
}
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
Solution2:
better
public void sortColors(int[] nums) {
int begin = 0;
int end = nums.length - 1;
for (int i = 0; i <= end; i++) {
while (nums[i] == 2 && i < end) {
swap(nums, i, end--);
}
while (nums[i] == 0 && i > begin) {
swap(nums, i, begin++);
}
}
}
private void swap1(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}