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.
(不能使用Arrays.sort(A),其实我有偷着用了一下,只需要写一行代码调用一下,但是运行时间也并没有很短啦)
/*方法一 :新建一个数组newA[],对A进行遍历,当元素为0,存入新数组头部,元素为2则存入新数组尾部,
最后将新数组中间部分都置为1,时间复杂度为O(n),runtime = 218ms*/
public class Solution {
public void sortColors(int[] A) {
int l = 0;
int i = 0;
int len = A.length;
int h = len - 1;
int newA[] = new int[len];
while (i < len){
if (A[i] == 0){
newA[l ++] = A[i];
}
if (A[i] == 2){
newA[h --] = A[i];
}
i ++;
}
while (l <= h){
newA[l] = 1;
l ++;
}
A = newA;
for (i = 0; i < len; i ++){
//A[i] = newA[i];
System.out.print(A[i] + " ");
}
}
}
/*方法二:新建一个数组count[],对A进行遍历,将0,1,2分别出现的次数存入新数组的0,1,2位置,
* 然后根据count值对A重新赋值,时间复杂度为O(n),runtime = 197ms */
public class Solution {
public void sortColors(int[] A) {
int count[] = new int[3];
int i = 0;
for(i = 0; i < A.length; i ++) {
count[A[i]]++;
}
int j = 0;
for (i = 0; i < 3; i++) {
while (count[i] > 0){
A[j ++] = i;
count[i] --;
}
}
}
}