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.
[Thoughts]:
You are not suppose to use the library's sort function for this problem.
public class Solution {
public void sortColors(int[] A) {
int n = A.length;
int i = 0; //0 pointer
int j = n - 1; //1 pointer
int k = n - 1; //2 pointer
while(i <= j){ // i <= j, because all the elements after j are 1 and 2, both greater than 1.
if(A[i] == 2){
swap(A, i, k);
k--;
if(k < j)//若是blue在white前面了,记得同时更新white
j = k;
}
else if(A[i] == 1){
swap(A, i, j);
j--;
}else
i++;
}
}
public void swap(int[] A, int a, int b){
int temp = A[a];
A[a] = A[b];
A[b] = temp;
}
}
No comments:
Post a Comment