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.
public class Solution {
public void sortColors(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A==null) return;
int[] flags = new int[3];
for(int i=0;i<A.length;i++){
flags[A[i]]++;
}
int start=0;
for(int i=0;i<3;i++){
for(int j=0;j<flags[i];j++){
A[start++]=i;
}
}
}
}
One-Pass Solution:
public class Solution {
public void sortColors(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A.length==0)return;
int i=0, j=A.length-1;
while(i<A.length && A[i]==0) i++;
int cur=i;
while(j>=0 && A[j]==2) j--;
while(cur<=j){
if(A[cur]<=A[i]){
swap(A,i,cur);
while(i<A.length && A[i]==0){
i++;
cur=i;
}
}
if(cur<=j && A[cur]>A[j]){
swap(A,cur,j);
while(j>=0 && A[j]==2)j--;
}else
cur++;
}
}
public void swap(int[] num, int a, int b){
int temp = num[a];
num[a] = num[b];
num[b] = temp;
}
}
No comments:
Post a Comment