题目:
Given an array with n objects colored red, white or blue, sort them in-place 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.
Example:
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
Follow up:
- 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 a one-pass algorithm using only constant space?
描述:
一个数组中有0,1,2 三种数字,请设计一个算法将三种数字按照升序排列,
要求时间复杂度为 O(n),空间复杂度常数级别
分析:
需要设置多个指针,
一个是数字0的右边界的右侧,设为zero,
一个是数字2的左边界的左侧,设为two,
一个是当前处理到的坐标,设为current,
思路不复杂,算法过程如下,
1,当current遇到0时,则这个0和zero位置元素交换,并且zero后移,
其中如果交换后,current位置仍为0,则current需要后移一位
2,若curren处为1,则current后移
3,若current处为2,则这个2和two位置元素交换,并且two前移
按上述三步循循环,直到current大于two
第一次见到这个题是在考研时的专业课复习书上,当时不是特别理解答案的思路,这次自己写出了完整的解法,发现其实也没有那么复杂,很多时候都是自己吓自己,别想太多,做就行了
代码:(时间复杂度 O(n), 空间复杂度 O(1))
class Solution {
public:
void sortColors(vector<int>& nums) {
int zero = 0, current = 0, two = nums.size() - 1;
while (current <= two) {
if (nums[current] == 0) {
swap(nums[current], nums[zero]);
if (nums[current] == 0) {
++current;
}
++ zero;
} else if (nums[current] == 1) {
++ current;
} else {
swap(nums[current], nums[two]);
-- two;
}
}
}
};