LeetCode:Sort Colors

本文介绍了一种不使用库排序函数的颜色排序算法,通过三种颜色(红、白、蓝)的整数表示,利用三个指针(start、mid、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.

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

思路1:

  1. 题目和荷兰国旗问题是相同的
  2. 采用三个指针start,mid,end来操作,依据nums[mid]的值来判断下一步的操作
  3. 当nums[mid]=0时,swap(nums[start],nums[mid]),start++,mid++
  4. 当nums[mid]=1时,mid++
  5. 当nums[end]=2时,swap(num[end],nums[mid]) end–

思路2:

  1. 三指针赋值更新办法
    这种方法很巧妙,自己动手走一个例子,慢慢理解
#include "stdafx.h"
#include "iostream"
#include "vector"
using namespace std;

class Solution {
public:
    //方法2
    void sortColors(vector<int>& nums)
    {
        int two = 0, one = 0, zero = 0;
        for (int num : nums)
        {
            if (num == 2) { two++; }
            if (num == 1) { nums[two++] = 2; nums[one++] = 1; }
            if (num == 0) { nums[two++] = 2; nums[one++] = 1; nums[zero++] = 0; }
        }
    }
    //方法1
    void sortColor(vector<int>& nums) {
        //the second solution
        int start = 0, end = nums.size() - 1, mid=0,tmp;
        while (mid <= end) {
            if (nums[mid] == 0) {
                //swap(nums[start++], nums[mid++]);
                tmp = nums[start];
                nums[start] = nums[mid];
                nums[mid] = tmp;
                mid++;
                start++;
            }
            else if (nums[mid] == 1)
            {
                mid++;
            }
            else if (nums[mid] == 2) {
                //swap(nums[mid], nums[end--]);
                tmp = nums[end];
                nums[end] = nums[mid];
                nums[mid] = tmp;
                end--;
            }

        }
    }
};

int main()
{
    vector<int> nums;
    nums.push_back(2);
    nums.push_back(2);
    nums.push_back(1);
    nums.push_back(0);
    nums.push_back(2);
    Solution sol;
    sol.sortColor(nums);
    for (int i=0; i < nums.size(); i++)
        cout << nums[i] << endl;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值