75.Sort Colors¶
Tags : Medium
Array
Two Pointers
Sort
Links: https://leetcode.com/problems/sort-colors/
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?
class Solution {
public:
void sortColors(vector<int>& nums) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = nums.size();
vector<int> store(3);
for (int i = 0; i < n; ++i) ++store[nums[i]];
int pos = 0;
for (int i = 0; i < 3; ++i) {
while (store[i]) {
nums[pos++] = i;
--store[i];
}
}
}
};
Follow Up相当于提示了使用桶排序,一次遍历统计数量,第二次遍历写入。
class Solution {
public:
void sortColors(vector<int>& nums) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = nums.size();
int zero = 0, two = n - 1;
for (int i = 0; i <= two; ++i) {
if (nums[i] == 0)
std::swap(nums[i], nums[zero++]);
else if (nums[i] == 2)
std::swap(nums[i--], nums[two--]);
}
}
};
一次遍历肯定想到的是双指针,一个指针zero
指向首段,一个指针two
指向尾端,从头开始遍历,遇到0就和zero
交换,遇到2就和two
交换。因为i
始终不小于zero
,所以无需额外操作,但是每次遇到2和two
,可能存在原来two
指向的就不符合顺序,所以此时需要让i
后退一步来检查是否符合要求。