Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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 supposed to use the library's sort function for this problem.

这题就是想把乱序的[2 2 1 0 1 1 0 2]排列成有序的[0 0 1 1 1 2 2 2].

方法一:两趟循环,第一趟数0,1,2的个数,第二趟修改数组A, 思想简单且无编程难度.
\(O(2n)\) time, \(O(1)\) extra space.

// two-pass algorithm
// [ 2 2 1 0 1 1 0 2]
void sortColors(vector<int>& A) {
	int c_0 = 0, c_1 = 0;

	for (int i = 0; i < A.size(); i++)
		if (A[i] == 0) c_0++;
		else if (A[i] == 1) c_1++;

	for (int i = 0; i < A.size(); i++)
		if (i < c_0) A[i] = 0;
		else if (i >= c_0 && i < (c_1 + c_0)) A[i] = 1;
		else A[i] = 2;
}

方法二,人家的想法了,就是扫描数组,发现2就送入队尾方向,发现0就送队首方向,最后1自然就在中间,就排好了.这方法编程不容易.

设定 zero = 0, sec = A.size()-1 两个指针.
若 A[i] = 2, swap(A[i], A(sec--));
若 A[i] = 0, swap(A[i], A(zero++));
// one-pass algorithm
// [ 2 2 1 0 1 1 0 2]
void sortColors(vector<int>& A) {
	int zero = 0, sec = A.size() - 1;
	for (int i = 0; i <= sec; i++) {
		while (A[i] == 2 && i < sec) swap(A[i], A[sec--]);
		while (A[i] == 0 && i > zero) swap(A[i], A[zero++]);
	}
}
posted on 2017-09-07 16:17  英雄与侠义的化身  阅读(117)  评论(0编辑  收藏  举报