Lintcode 148. 颜色分类
题目描述:给定一个包含红,白,蓝且长度为 n 的数组,将数组元素进行分类使相同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数 0,1 和 2 分别代表红,白,蓝。
- 不能使用代码库中的排序函数来解决这个问题。
- 排序需要在原数组中进行。
这道题因为值是可数的整数,所以最简单直接的方法就可以用题目描述中所说的计数方法,扫一遍统计0,1,2各有多少个,然后再扫一遍依次用0,1,2去覆盖,这种方法应该叫计数排序。
另外,还有一种方法是采用【两根指针——快速选择系列】Lintcode 31. 数组划分 这道题的2根指针实现分割的办法,分割两次,第一回将0放到数组左边,1和2混在一起的放在数组右边,第二回将1和2混在一起的部分,分割出1和2来。这样也能实现。
下面采用的方法是,只扫描一遍就能得到结果的方法,用了3根指针。
解题思路:使用一次扫描的办法。 设立三根指针,left, index, right。定义如下规则:
- left 的左侧都是 0(不含 left)
- right 的右侧都是 2(不含 right)
index 从左到右扫描每个数,如果碰到 0 就丢给 left,碰到 2 就丢给 right。碰到 1 就跳过不管。
class Solution {
public:
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
void sortColors(vector<int> &nums) {
if (0 == nums.size()) {
return;
}
int left = 0, right = nums.size() - 1, index = 0;
while (index <= right) {
if (nums[index] == 0) {
swap(nums[left], nums[index]);
left++;
index++;
} else if (nums[index] == 1) {
index++;
} else if (nums[index] == 2) {
swap(nums[index], nums[right]);
right--;
}
}
}
};