Leetcode 75 Sort Colors

本文探讨了三种不同的算法来解决颜色排序问题:冒泡排序、桶排序和原地排序。通过这些方法,可以有效地将红色(0)、白色(1)和蓝色(2)这三种颜色的对象按顺序排列。

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

排序的问题,我直接用了最简单的冒泡。

实际上还是有其他的方法的。

public class Solution {
    public void sortColors(int[] nums) {
        for(int i = 0; i<nums.length; i++){
            for(int j = i + 1; j< nums.length; j++){
                if(nums[i]>nums[j]){
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
        }
    }
}


比如使用bucket的方法


private static final int MAX = 3;

public void sortColors(int[] nums) {
    int[] buckets = new int[MAX];
    for(int num : nums) buckets[num]++;
    for(int p = 0, val = 0; val < MAX; val++) {
        for(int count = 0; count < buckets[val]; count++) {
            nums[p++] = val;
        }
    }
}

// one pass in place solution
void sortColors(int A[], int n) {
    int j = 0, k = n - 1;
    for (int i = 0; i <= k; ++i){//只有当i当前指向的元素为1的时候才会移动
        if (A[i] == 0 && i != j)//当ij不等的时候 i至少会比j多加一次 因此 i会在j的后面
            swap(A[i--], A[j++]);//i保持不动 队首指针后移
        else if (A[i] == 2 && i != k)//找到2 就放在最后面
            swap(A[i--], A[k--]);//队尾指针前移  i保持不动
    }
}

// one pass in place solution
void sortColors(int A[], int n) {
    int j = 0, k = n-1;
    for (int i=0; i <= k; i++) {
        if (A[i] == 0)
            swap(A[i], A[j++]);
        else if (A[i] == 2)
            swap(A[i--], A[k--]);
    }
}


题外话,好久不刷题,被炼狱级别的workload吓疯了。

我总是处于各种焦虑的状态,担心着很久很久以后的事情。

似乎我们从一生下来就被赶着走,没人问你开不开心,只关心你够不够达到人们觉得的“优秀”。

我不知道自己是不是真的开心。

我走得一帆风顺,似乎是,又似乎不是自己想要的东西。

希望能坚持吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值