您的位置:首页 > 其它

[LeetCode] Sort Colors

2015-06-09 14:31 323 查看
The hints on below the problem have suggested a two-pass solution.

Now I will focus on the one-pass solution.

The one-pass solution has no mystery. Just swap all 0's to the left and all 2's to the right and the 1's will automatically fall in the middle.

Now comes the following code. You may play with it using some examples on a paper to see how it works.

void sortColors(vector<int>& nums) {
int red = 0, blue = nums.size() - 1;
for (int i = 0; i <= blue; i++) {
while (nums[i] == 2 && i < blue)
swap(nums[i], nums[blue--]);
while (nums[i] == 0 && i > red)
swap(nums[i], nums[red++]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: