75. Sort Colors

来源:互联网 发布:sm2算法原理 编辑:程序博客网 时间:2024/06/17 23:48

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.

click to show follow up.

Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

Could you come up with an one-pass algorithm using only constant space?

这道题的大致思路是遍历数组,把所有的0放到数组前面,把所有的2放到数组后面。思路比较容易,但实现起来需要仔细考虑一些细节。起初想用stl的数组操作的函数实现,出了很多问题,后来参考其他答案,找到了一个相对好理解的方法。
详解可以参考:Sharing C++ solution with Good Explanation

class Solution {public:    void sortColors(vector<int>& nums) {        /*分别用low,high,mid记录当前排序的状态,low之前是以及排号的0,high之后是已经排好的2,mid和high之间是尚未排序的数*/        int low = 0, high = nums.size() - 1, mid = 0;        while (mid <= high) {            if (nums[mid] == 0) {                /*此时nums[mid]==0,nums[low]==1,两者交换*/                nums[mid] = nums[low];                nums[low] = 0;                mid++;                low++;            }            else if (nums[mid] == 2) {                nums[mid] = nums[high];                nums[high] = 2;                /*mid不能加一,因为交换之后nums[mid]可能等于0,还需要与nums[low]交换*/                high--;            }            else {                mid++;            }        }    }};