leetcode【第十三周】颜色排序

本文介绍了一种特定场景下的排序算法——三色排序,该算法针对红、白、蓝三种颜色的对象进行排序,使得相同颜色的对象相邻,并按红、白、蓝的顺序排列。文中提供了几种不同的实现方式,包括计数排序、冒泡排序以及一种利用两个指针的优化方法。

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

Note:
You are not suppose to use the library's sort function for this problem.

click to show follow up.

Follow up:
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?


问题分析:

一开始没看follow up,想到只是单纯的数字由小到大的排序问题,直接随便写了个冒泡排序,过了只要3ms,然后看到说直观的做法是使用计数排序【话说直观为何会想到这个...】,所以又写了下计数,时间跟普通的冒泡也差不多,还是3ms。某种程度上来说,冒泡跟计数一样,都是扫两遍,所以时间差不多道也可以理解。


具体实现:

计数:

class Solution {
public:
    void sortColors(vector
  
   & nums) {
        
        int i=0;
        int j=0;
        int k=0;
        for(int p=0;p
   
  

冒泡:

class Solution {
public:
    void sortColors(vector
  
   & nums) {
        
        int tmp = -1;
        for(int i=0;i
   
     nums[j])
                {
                     tmp = nums[j];
                     nums[j] = nums[i];
                     nums[i] = tmp;
                }
            }
        }
        
    }
};
   
  

双冒泡:

class Solution {
public:
    void sortColors(vector
  
   & nums) {
        int low = 0;
        int high = nums.size()-1;
        int tmp,j;
        while(low
   
    nums[j+1])
                {
                    tmp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = tmp;
                }
            }
            high--;
            for(j = high;j>low;--j)
            {
                if(nums[j]
    
   
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值