Sort Colors -- Leetcode

本文介绍了一种高效算法,用于将数组中不同颜色的对象按颜色顺序排列,确保同一颜色的对象相邻。算法利用双指针技巧,通过交换操作实现排序,避免了使用库函数。该方法特别适用于解决包含三种颜色的排序问题,且不适用于更多颜色的情况。

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

12.24 2014

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.

class Solution {
public:
    void sortColors(int A[], int n) {
        int red=0;
        int blue=n-1;
        int i=0;
        while(i<blue+1){
            if(A[i]==0){
                swap(A[i],A[red]);
                red++;
                i++;
            }
            else if(A[i]==2){
                swap(A[i],A[blue]);
                blue--;
            }
            else
                i++;
        }
    }
};
总结:

1. 思路:使用两个指针记录下一个红色和蓝色放的位置,红色起始位置为0,蓝色的为最后一位。当遇到是红色,则交换当前值,把他放到更靠近左边的位置,并更新red的index,和将考察element移到下一个;如果遇到蓝色,则交换当前值,但是由于不知道当前值是什么,所以只更新下一个蓝色该放得位置,但要继续考察被交换以后的当前index对应的值。若遇到白色,只是单纯的考察下一个element。

2. 该方法无法推广到多种颜色。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值