【Leetcode】之Sort Colors

本文介绍了一种特殊的三色排序问题,即给定一个包含红色、白色和蓝色对象的数组,要求将相同颜色的对象相邻排列,并按红白蓝顺序输出。提供两种解决方案,一种为两遍扫描法,时间复杂度O(n),另一种为单遍扫描法,仅需遍历数组一次。

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

二.我的解题思路

这道题挺特殊的,我采用的是很简单的解法。先遍历整个vector,得到0,1,2的个数,然后再遍历一次进行赋值即可。这种做法的时间复杂度是O(n),但是需要遍历整个数组两次才行。测试通过的程序如下:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int len = nums.size();
   
        
        int num0,num1,num2; num0=num1=num2=0;
        for(int i=0;i<len;i++){
            if(nums[i]==0) num0++;
            if(nums[i]==1) num1++;
            if(nums[i]==2) num2++;
        }
        int idx[3]={0,num0,num0+num1};
         for(int i=0;i<len;i++){
            if(i<num0) nums[i]=0;
            if(i>=num0 && i<(num0+num1)) nums[i]=1;
            if(i>=(num0+num1)) nums[i]=2;
                
        }
        
    }
    

  
  
};
后来又在网上看到别人比较牛逼的思路:

class Solution {
public:
	void sortColors(vector<int>& A) {
		int len = A.size();
		int i = -1;
		int j = -1;
		int k = -1;
		for (int p = 0; p < len; p++)
		{
			//根据第i个数字,挪动0~i-1串。
			if (A[p] == 0)
			{
				A[++k] = 2;    //2往后挪
				A[++j] = 1;    //1往后挪
				A[++i] = 0;    //0往后挪
			}
			else if (A[p] == 1)
			{
				A[++k] = 2;
				A[++j] = 1;
			}
			else
				A[++k] = 2;
		}

	}

};
这种思路是判断0,1,2需要往后挪动的次数,只需要遍历整个数组一次即可。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值