【力扣】75.颜色分类

题目描述

给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

我们使用整数 012 分别表示红色、白色和蓝色。

必须在不使用库内置的 sort 函数的情况下解决这个问题。

示例 1:

输入 :nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]

示例 2:

输入 :nums = [2,0,1]
输出:[0,1,2]

提示:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] 为 0、1 或 2

进阶:

你能想出一个仅使用常数空间的一趟扫描算法吗?

解题方案

快速排序

  • C 冒泡排序法
c 复制代码
void bubbleSort(int *array, int size)
{
    for (int step = 0; step < size - 1; ++step)
    {
        // 在每一轮中,最大的元素会冒泡到最后
        for (int i = 0; i < size - step - 1; ++i)
        {
            // 根据元素值比较和交换位置
            if (array[i] > array[i + 1])
            {
                // 使用异或操作交换两个元素,不需要额外的存储空间
                array[i] = array[i] ^ array[i + 1];
                array[i + 1] = array[i] ^ array[i + 1];
                array[i] = array[i] ^ array[i + 1];
            }
        }
    }
}

void sortColors(int* nums, int numsSize)
{
    bubbleSort(nums, numsSize);     // 冒泡排序
}

复杂度分析

时间复杂度平均情况下为 O(n2),其中 n 是数组 nums 的长度。

空间复杂度为 O(1),不需要额外的存储空间。

  • C 单指针法
c 复制代码
void swap(int *a, int *b)   // 交换函数
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void sortColors(int *nums, int numsSize)
{
    int ptr = 0;
    for (int i = 0; i < numsSize; ++i)      // 第一次遍历
    {
        if (nums[i] == 0)
        {
            swap(&nums[i], &nums[ptr]);     // 将 0 移动到前端
            ++ptr;
        }
    }
    for (int i = ptr; i < numsSize; ++i)    //第二次遍历
    {
        if (nums[i] == 1)
        {
            swap(&nums[i], &nums[ptr]);     // 将 1 移动到前端
            ++ptr;
        }
    }
}

复杂度分析

时间复杂度为O(n),其中 n 是数组 nums的长度。

空间复杂度为O(1),不需要额外的存储空间。

  • C 双指针
c 复制代码
void swap(int *a, int *b)   // 交换函数
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void sortColors(int *nums, int numsSize)
{
    int head = 0, tail = numsSize - 1;
    for (int i = 0; i <= tail; )            // 一次遍历
    {
        if (nums[i] == 0)
        {
            swap(&nums[i], &nums[head]);     // 将 0 移动到前端
            head++;
            i++;
        }
        else if (nums[i] == 2)
        {
            swap(&nums[i], &nums[tail]);     // 将 2 移动到尾端
            tail--;
        }
        else
        {
            i++;
        }
    }
}

复杂度分析

时间复杂度为O(n),其中 n 是数组 nums的长度。

空间复杂度为O(1),不需要额外的存储空间。

相关推荐
玉树临风ives1 分钟前
atcoder ABC 457 题解
数据结构·c++·算法
禧西27 分钟前
面试准备——agent和大模型_1
面试·职场和发展
宵时待雨42 分钟前
回溯算法专题1:递归
数据结构·c++·笔记·算法·leetcode·深度优先
爱思德学术1 小时前
【SPIE出版】黄冈师范学院主办!第四届大数据、计算智能与应用国际会议(BDCIA 2026)
大数据·算法·数据分析·云计算·etl
洛水水1 小时前
【力扣100题】40.二叉树中的最大路径和
算法·leetcode·深度优先
洛水水1 小时前
【力扣100题】37.从前序与中序遍历序列构造二叉树
c++·算法·leetcode
zyq99101_11 小时前
递归与动态规划实战代码解析
python·算法·蓝桥杯
一只机电自动化菜鸟1 小时前
一建机电备考笔记(34)焊接技术(设备与材料1)(含考频+题型)
笔记·学习·职场和发展·生活·学习方法
橘白3161 小时前
rl笔记(一):策略梯度更新算法推导
人工智能·算法·机器人·强化学习
hhhhhaaa1 小时前
多节点矩阵式任务系统:统一配置中心与动态规则引擎架构设计
后端·算法·架构