题目
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.
思路
LeetCode的discuss里有一个很好的思路,效率不高,但是便于理解,记录在这里:链接
代码
class Solution {
public:
void sortColors(vector<int>& nums) {
int r = 0;
int w = 0;
int b = nums.size() - 1;
while (w <= b) {
if (nums[w] == 2) {
int tmp = nums[w];
nums[w] = nums[b];
nums[b] = tmp;
b--;
} else if (nums[w] == 0) {
int tmp = nums[w];
nums[w] = nums[r];
nums[r] = tmp;
r++;
w++;
} else if (nums[w] == 1) {
w++;
}
}
}
};