LeetCode题解:Sort Colors

本文介绍了一种有效的三色排序算法,该算法可以在一次遍历数组的过程中实现红、白、蓝三色的排序,且不使用额外的排序库函数。通过设定两个指针,一个用于跟踪0的最后位置,另一个用于跟踪2的起始位置,以此实现原地排序。

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

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的个数,然后再次遍历数组,按照0,1,2的个数再分别填回。这样时间复杂度是O(2n)。

题目中希望能够一次遍历数组就解决这个问题。这样就得考虑利用数组里只有三种不同的值的情况。采用一个类似快速排序的方法。

首先设定两个指针。第一个指针last0,在指针及其左边的数字都是0。第二个指针first2,在指针及其右边的数字都是2。

现在用一个指针i遍历last0和first2之间的数字。如果这个数字是2,则让first2左移一位,交换first2和i指向的值,同时重新检查i的值。如果这个数字是0,则让last0右移一位。这时有两种情况。第一种情况,last0和i重合,那么直接检查下一个数字即可。反之,右移后的last0必然指向的值是1,将last0和i交换。

这样,在循环过程中,last0及其左边的数字必然是0,last0和i之间的数字如果有的话必然是1,first2及其右边的数字必然是2。在i和last0重合的时候,排序完成。

题解:

class Solution {
public:
    void sortColors(int A[], int n) {
        if (n == 0)
            return;
    
        int last0 = 0;
        while(A[last0] == 0) ++last0;
        last0--;    // jump back to 0
    
        int first2 = n-1;
        while(A[first2] == 2) --first2;
        first2++;   // jump forward to 2
    
        int i = last0 + 1;
        while(i < first2)
            if (A[i] == 2 )
                swap(A[i], A[--first2]);
            else if (A[i] == 0)
                swap(A[i++], A[++last0]);
            else
                ++i;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值