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.
Note:
You are not suppose to use the library's sort function for this problem.
You are not suppose to use the library's sort function for this problem.
i0 points to 0 while i2 points to 2; i sweeps from left to right; note that i++ exist only when meets 0 or 1.
////////////////////////////////////////
// codes
class Solution {
public:
void sortColors(vector<int>& nums) {
int i0 = 0, i2 = nums.size()
- 1;
for (int i = 0; i <= i2;){
if (nums[i] == 0){
swap(nums[i], nums[i0]);
++i0;
continue;
}
else if (nums[i] ==
2){
swap(nums[i], nums[i2]);
--i2;
continue;
}
++i;
}
}
};
No comments:
Post a Comment