题目:
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[] nums) {
int redCount=0;
int whiteCount=0;
int blueCount=0;
for(Integer i: nums){
if(i==0) redCount++;
else if(i==1) whiteCount++;
else if(i==2) blueCount++;
}
for(int i=0;i<nums.length;i++){
if(i<redCount) nums[i]=0;
else if(i<redCount+whiteCount) nums[i]=1;
else
nums[i]=2;
}
}
}
解决方法二: Runtime: 1 ms
public class Solution {
public void sortColors(int[] nums) {
int redCount=0;
int blueCount=nums.length-1;
for(int i=0;i<=blueCount;i++){
while(nums[i]==2&&i<blueCount){
nums[i]^=nums[blueCount];
nums[blueCount]^=nums[i];
nums[i]^=nums[blueCount];
blueCount--;
}
while(nums[i]==0&&i>redCount){
nums[i]^=nums[redCount];
nums[redCount]^=nums[i];
nums[i]^=nums[redCount];
redCount++;
}
}
}
}
参考:
本文介绍了一种不使用库排序函数的三色排序算法,通过两种不同的实现方式来确保相同颜色的对象相邻并按红、白、蓝顺序排列。方法一利用计数排序思想,统计每种颜色的数量再重新填充数组;方法二是采用双指针技术,在一次遍历中完成排序。
1892

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



