public class Solution {
public void sortColors(int[] A) {
int countRed = 0;
int countBlue = 0;
int countBlack = 0;
for(int i = 0 ;i < A.length ;i++){
switch(A[i]){
case 0: countRed++;break;
case 1: countBlue++;break;
case 2: countBlack++;break;
default:break;
}
}
for(int i = 0 ; i < A.length ;i++){
if(countRed > 0 ){
A[i] = 0;
countRed--;
}else if(countBlue > 0){
A[i] = 1;
countBlue--;
}else if(countBlack > 0){
A[i] = 2;
countBlack--;
}
}
}
}
上面是two-pass方法
Sort Colors
最新推荐文章于 2021-04-15 12:30:39 发布