leetcode 十一周解题报告

本文介绍了一种针对红、白、蓝三种颜色对象的排序算法,通过模仿快速排序中的分区思想,实现相同颜色对象相邻且按红、白、蓝顺序排列。文章详细解释了算法的实现过程,并给出了具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

75. Sort Colors

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.


解题思路:

仿照快排的partition解题,调用三次即可解决问题,复杂度O(n)

class Solution {
public:
    void sortColors(vector<int>& nums) {
       int mid = partition(nums, 1, 0, nums.size() - 1);
       partition(nums, 0, 0, mid);
       partition(nums, 2, mid, nums.size() - 1);
    }
    int partition(vector<int>& nums, int pivot, int begin, int end) {
        //int end = nums.size() - 1;
        while(end > begin){
            while(end > begin && nums[end] >= pivot) --end;
            while(end > begin && nums[begin] < pivot) ++begin;
            int tmp = nums[begin];
            nums[begin] = nums[end];
            nums[end] = tmp;
        }
        return begin;
    }
};
结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值