Sort Colors问题及解法

来源:互联网 发布:idea如何新建java项目 编辑:程序博客网 时间:2024/05/18 00:54

问题描述:

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.

问题分析:

对于2,我们可以一直放数组右边,对于0,我们可以一直放数组左边。


过程详见代码:

class Solution {public:    void sortColors(vector<int>& nums) {       int right = nums.size() - 1;int left = 0;for (int i = 0; i <= right;i++){while (nums[i] == 2 && i < right) swap(nums[i], nums[right--]);while (nums[i] == 0 && left < i) {swap(nums[i], nums[left++]); }}     }};