LeetCode 75. Sort Colors
Given an array nums 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
.
We will use the integers 0, 1, and 2
to represent the color red, white, and blue, respectively.
You must solve this problem without using the library’s sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
method
让zero, one, two
分别为0,1,2
的末尾指针,遍历数组
- 如果是0,则
zero++, one++, two++
- 如果是1,则
one++, two++
- 如果是2,则
two++
void sortColors(vector<int>& nums) {
int zero = -1;
int one = -1;
int two = -1;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 0) {
nums[++two] = 2;
nums[++one] = 1;
nums[++zero] = 0;
}
else if (nums[i] == 1) {
nums[++two] = 2;
nums[++one] = 1;
}
else {
nums[++two] = 2;
}
}
}
two/one/zero
指针移动的先后顺序不能修改,例如一开始的时候来个0
,那如果zero
先移动赋值,后面就会被one
和two
覆盖了