Title Description
Change the title is taken from the Dutch flag issue
Given a red, white and blue, a total of n elements of the array, sorts them in situ, such that adjacent elements with the same color and arranged in a red, white, blue order.
This question, we use an integer of 0, 1 and 2 represent the red, white and blue.
Note:
You can not use the sort function code base to solve this question.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Advanced:
An intuitive solution is to count twice scanning algorithm using ordered.
Firstly, the iterative calculation of the number of elements 0, 1 and 2, and then sorted 0,1,2, overwriting the current array.
Can you think of a single pass using only constant space algorithm do?
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/sort-colors
Thinking
-
Counting sort, but it needs to scan twice, although able to ac, but substandard meaning of the questions;
-
Since only three colors, it is possible to record index, a is 0 (red) of the index, the other 2 (blue) of the index, go to the middle of the two pointers. We used three pointers 0 (red) rightmost border, 2 (blue) in the most left boundary, and the current pointer data (red, blue, curr) respectively recorded.
The rightmost border initialization 0: red = 0. Throughout the execution of the algorithm nums [idx <red] = 0.
Initialization leftmost border 2: blue = n - 1. Throughout the execution of the algorithm nums [idx> blue] = 2.
Initialize the current element number is considered: curr = 0.
While curr <= blue:
If nums [curr] = 0: switching the first and second red curr th element, and the pointer to the right.
If nums [curr] = 2: exchange of curr th and blue elements, the pointer to the left and blue.
If nums [curr] = 1: The pointer curr right.
c++
// 两趟算法
class Solution {
public:
void sortColors(vector<int>& nums) {
int counts[3] = {0};
for(int i = 0; i < nums.size();++ i){
counts[nums[i]] ++;
}
for(int i = 0, index = 0; i < 3;++ i){
for(int j = 0; j < counts[i]; ++ j)
nums[index ++] = i;
}
}
};
// 双指针
class Solution {
public:
/*
荷兰三色旗问题解
*/
void sortColors(vector<int>& nums) {
int red = 0, curr = 0;
int blue = nums.size() - 1;
while (curr <= blue) {
if (nums[curr] == 0) {
swap(nums[curr++], nums[red++]);
}
else if (nums[curr] == 2) {
swap(nums[curr], nums[blue--]);
}
else curr++;
}
}
};