题目描述:
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.
Notice
You are not suppose to use the library's sort function for this problem.
You should do it in-place (sort numbers in the original array).
Given [1, 0, 1, 2]
, sort it in-place to [0, 1, 1, 2]
.
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
题目要求one-pass,我想如果用一个map去存0,1,2各出现过多少次的话,必须要用two-pass以上,那么用counter去存出现多少次肯定不可行。幸好这题中color只有三种:0,1,和2, 那么可以想到用two pointers的办法,l pointer始终在可以放0的位置,r pointer始终在可以放2的位置,用i去遍历整个数组(i必须小于等于r,因为r之后的数都已经分配好了),如果i遍历到了0,那么把位置i和位置l上的数对换;如果i遍历到了1,那么把位置i和位置 r上的数对换。这里需要注意的是,l换给i的数肯定不是2,因为i始终走在l的前面,如果有2早就换给r了;但是r换给i的数可能是0,因为r始终在i的前面,所以r和i换完后,i不能++,得再查一遍它是否换了0给i。
Mycode(AC = 70ms):
class Solution{
public:
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
void sortColors(vector<int> &nums) {
// write your code here
// put the 0's to head, 1's to tail
int l = 0, r = nums.size() - 1;
for (int i = 0; i <= r; i++) {
if (nums[i] == 0) {
swap(nums, l, i);
l++;
}
else if (nums[i] == 2) {
swap(nums, r, i);
r--;
i--;
}
}
}
void swap(vector<int> &nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};