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.
Seen this question in a real interview before?
三种数字的排序,用三个指针做交换即可
public class Solution {
public void sortColors(int[] nums) {
if(nums.length<2)return ;
int l = nums.length-1;
int nr = 0;
int nb = nums.length-1;
while(nr<=l&&nums[nr]==0)nr++;
while(nb>=0&&nums[nb]==2)nb--;
int nw = nr;
while(nw<=nb){
if(nums[nw]==1){
nw++;
continue;
}
if(nums[nw]==0){
nums[nw] = nums[nr];
nums[nr] = 0;
nr++;
nw++;
}
else{
nums[nw] = nums[nb];
nums[nb] = 2;
nb--;
}
}
return ;
}
}
本文介绍了一种不使用库排序函数的三色数组排序算法。该算法通过三个指针实现不同颜色对象的相邻排序,确保了排序后的数组符合红、白、蓝的颜色顺序。
3114

被折叠的 条评论
为什么被折叠?



