Sort Colors

本文介绍了一种不使用内置排序函数解决红白蓝三色排序问题的方法。通过计数排序算法,实现相同颜色相邻且按红白蓝顺序排列。文章详细讲解了计数排序的具体步骤,并提供了完整的Java代码实现。
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.

解决这道题目我们可以采用计数排序算法。首先我们遍历数组得到每个颜色的个数,记录到计数数组count[i]中;接下来我们累加计数数组,使count[i] = count[i] + count[i - 1],这样其实就是给不同的元素给定了不同大小的空间;然后我们遍历需要排序的数组,用一个临时数组tem[]记录遍历过的元素,使tem[--count[nums[i]]] = nums[i];这样相当于将每种颜色从它所属的空间后面开始填充,直到结束。代码如下:

public class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0)
return ;
int[] count = new int[3];
int[] tem = new int[nums.length];
for(int i = 0; i < nums.length; i++)
count[nums[i]] ++;
for(int i = 1; i < 3; i++)
count[i] = count[i] + count[i - 1];
for(int i = 0; i < nums.length; i++)
tem[--count[nums[i]]] = nums[i];
System.arraycopy(tem, 0, nums, 0, tem.length);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值