LeetCode-Sort Colors

本文介绍了一种有效的三色排序算法,该算法可以在一次遍历中完成对红、白、蓝三色(用0、1、2表示)的数组排序。通过使用两个指针分别指向已排序的0和2的边界,可以高效地实现相同颜色相邻且按顺序排列的目标。

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

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.

brute force的方法就是一遍把三种颜色都数一遍, 然后再一遍一个一个赋值。走一遍的方法就是两个指针,一个在前面指排好的0的末尾,另一个在后面指排好的2的最前面,只要是遇到0 2 就swap,1就不用管。注意要用while,就是可能换过来的那个数字也要继续swap。同时两个while的先后顺序是有关系的,要先处理好2的情况,再swap所有0的情况。因为有可能从后面swap 2的时候,换过来一个0,但是不可能swap 0的时候从前面换过来一个2.因为current指的位置之前只可能有0和1.

public class Solution {
    public void sortColors(int[] A) {
        if (A ==null || A.length == 0)
            return;
        int first = 0;
        int last = A.length -1;
        for ( int i = 0; i <= last; i ++){
                while ( A[i] == 2 && i < last){
                    int temp = A[i];
                    A[i] = A[last];
                    A[last] = temp;
                    last --;
                }
                while ( A[i] == 0 && i > first){
                    int temp = A[i];
                    A[i] = A[first];
                    A[first] = temp;
                    first ++;
                }
        }
    }
}
还有一个解法没仔细研究 感觉不太好想。

void sortColors(int A[], int n) {
    int n0 = -1, n1 = -1, n2 = -1;
    for (int i = 0; i < n; ++i) {
        if (A[i] == 0) 
        {
            A[++n2] = 2; A[++n1] = 1; A[++n0] = 0;
        }
        else if (A[i] == 1) 
        {
            A[++n2] = 2; A[++n1] = 1;
        }
        else if (A[i] == 2) 
        {
            A[++n2] = 2;
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值