75. Sort Colors

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++;
            }
        }
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值