#148 Sort Colors

本文介绍了一种有效的单遍算法来解决三色排序问题,即在原地将红色、白色和蓝色对象按顺序排列,使用0、1和2分别代表三种颜色。通过两个指针的方法,该算法能在常数空间复杂度内完成排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given an array with n objects colored redwhite 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 01, and 2 to represent the color red, white, and blue respectively.

 Notice

You are not suppose to use the library's sort function for this problem. 
You should do it in-place (sort numbers in the original array).

Example

Given [1, 0, 1, 2], sort it in-place to [0, 1, 1, 2].

Challenge 

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?

题目思路:

题目要求one-pass,我想如果用一个map去存0,1,2各出现过多少次的话,必须要用two-pass以上,那么用counter去存出现多少次肯定不可行。幸好这题中color只有三种:0,1,和2, 那么可以想到用two pointers的办法,l pointer始终在可以放0的位置,r pointer始终在可以放2的位置,用i去遍历整个数组(i必须小于等于r,因为r之后的数都已经分配好了),如果i遍历到了0,那么把位置i和位置l上的数对换;如果i遍历到了1,那么把位置i和位置 r上的数对换。这里需要注意的是,l换给i的数肯定不是2,因为i始终走在l的前面,如果有2早就换给r了;但是r换给i的数可能是0,因为r始终在i的前面,所以r和i换完后,i不能++,得再查一遍它是否换了0给i。

Mycode(AC = 70ms):

class Solution{
public:
    /**
     * @param nums: A list of integer which is 0, 1 or 2 
     * @return: nothing
     */    
    void sortColors(vector<int> &nums) {
        // write your code here
        // put the 0's to head, 1's to tail
        int l = 0, r = nums.size() - 1;
        for (int i = 0; i <= r; i++) {
            if (nums[i] == 0) {
                swap(nums, l, i);
                l++;
            }
            else if (nums[i] == 2) {
                swap(nums, r, i);
                r--;
                i--;
            }
        }
    }
    
    void swap(vector<int> &nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值