算法设计课第三周作业
一、题目介绍
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时,就先把2往后“挪”一个位置,再把1往后“挪”一个位置,最后再把0放在出现的空位上,也就是原本所有已经出现了的0的队列的最后;
- 任一时刻发现1时,就先把2往后“挪”一个位置,最后再把1放在出现的空位上,也就是原本所有已经出现了的1的队列的最后;
- 任一时刻发现2时,直接把2放到原本所有已经出现了的2的队列的最后。
四、代码展示
class Solution {
public:
void sortColors(vector<int>& nums) {
int p0 = -1, p1 = -1, p2 = -1;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 0) {
nums[++p2] = 2;
nums[++p1] = 1;
nums[++p0] = 0;
}
else if (nums[i] == 1) {
nums[++p2] = 2;
nums[++p1] = 1;
}
else {
nums[++p2] = 2;
}
}
}
};
五、代码解析
- p0、p1、p2 分别表示当前时刻已经出现了的0、1、2的队列的末尾的位置;
- 按照解题思路中的描述,当出现0时,把2和1的队列按照先后顺序往后移动一个位置,再把0放到0队列末端。
- 1、2 同理。