leetcode:Sort Colors

本文介绍了一种经典的排序算法——荷兰国旗问题的解决方案。该算法将一个包含红色、白色和蓝色的对象数组进行排序,使相同颜色的对象相邻,并按红、白、蓝的顺序排列。通过使用三个指针begin、current和end,有效地实现了排序。

摘要生成于 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.

本题为经典的荷兰国旗问题,当我们将红白蓝三色想象成条状物,有序排序后正好是荷兰国旗。解决这个问题,类似于快排中的partion过程,不过这里需要三个指针:begin, current, end. begin与current初始化为数组首部,end为数组尾部。具体算法如下:

1. cur=1时, cur++;

2. cur=0时, cur与begin交换值,并且cur++, begin++;这种情况下,cur与begin的值有两种情况,(1) cur与begin都为0;(2) cur为0,begin为1;

3. cur=2时, cur与end交换值,此时cur不变,end--;

具体代码如下:

class Solution {
public:
    void sortColors(int A[], int n) {
        int begin=0, cur=0,end=n-1;
        
        while(cur<=end)
        {
          if(A[cur]==1) cur++;
          else if(A[cur]==0)
          {
              swap(A[cur],A[begin]);
              cur++;
              begin++;
          }
          else
          {
              swap(A[cur],A[end]);
              end--;
          }
        }
    }
    
    void swap(int &a, int &b)
    {
        int tmp=a;
        a=b;
        b=tmp;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值