75. Sort Colors

来源:互联网 发布:软件开发风险分析 编辑:程序博客网 时间:2024/06/06 23:56

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.


由题意得,题目是要给出一些关于0,1,2的无序序列,然后要求对它们进行排序,其实这种只有三种数而且还是相邻的,用计数排序是最容易理解的,但是计数排序需要循环两次,题目要求循环一次就排出来。但是还是先写计数排序来试一试,代码如下。

Code(LeetCode运行3ms)

void sortColors(vector<int>& nums) {        int count[3] = {0};        for (int i = 0; i < nums.size(); i++) {            count[nums[i]]++;        }        int index = 0;        for (int i = 0; i < 3; i++) {            for (int j = 0; j < count[i]; j++) {                nums[index++] = i;            }        }
从结果来看,AC了,但是其实是不太符合题目要求的。所以又换一种循环一次的做法。就是用两个标记位,分别标记0的开始位置和2的终止位置,初始值是数组的开头和结尾。假如nums[i]为0,那么就把它和0的标记位的数进行交换,如果nums[i]是2的话,那么就和2的标记位交换,然后标记位减一,表示后面的数已经都是2了。代码如下。

Code(LeetCode运行3ms)

void sortColors(vector<int>& nums) {        int red = 0; //0的开始        int blue = nums.size() - 1; //2的结尾,从两边同时计算。        for (int i = 0; i < blue + 1;) {            if (nums[i] == 0) {                swap(nums[red++], nums[i++]);            } else if (nums[i] == 2) {                swap(nums[blue--], nums[i]);            } else {                i++;            }        }    }



原创粉丝点击