Description:
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.
Solution:
这道题目要求比较高的解法是在不使用额外空间的情况下,只是扫一遍就把结果得出。
一开始的想法是维护两个指针,分别是0和2的边界指针,有点类似与快速排序中指针使用的感觉。
然后网上看到了一个更加简洁的写法,这里拿来使用了一下,感觉有点说不清,大家就看代码感受一下吧。
import java.util.*;
public class Solution {
public void sortColors(int[] nums) {
int zero = 0, one = 0, temp;
for (int i = 0; i < nums.length; i++) {
temp = nums[i];
nums[i] = 2;
if (temp == 0) {
nums[one++] = 1;
nums[zero++] = 0;
} else if (temp == 1) {
nums[one++] = 1;
}
}
}
}