Leetcode 75. Sort Colors

本文详细解析了LeetCode中Sort Colors问题的解决方案,即著名的三色排序问题,亦称荷兰国旗问题。文章提供了一种使用三个指针进行原地排序的算法,时间复杂度为O(n),空间复杂度为O(1)。该算法通过一次遍历即可完成红、白、蓝三种颜色的排序,避免了使用额外的空间。

题目

链接:https://leetcode.com/problems/sort-colors/

Level: Medium

Discription:
Given an array with n objects colored red, white or blue, sort them in-place 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.

Example 1:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Note:

  • You are not suppose to use the library's sort function for this problem.
  • Could you come up with a one-pass algorithm using only constant space?

代码

class Solution {
public:
    void sortColors(vector<int>& nums) {
        if(nums.size()<=1)
            return;
        int fa=0;
        int fc=nums.size()-1;
        int fb=0;
        while(fb<=fc)
        {
            if(nums[fb]==0)
            {
                swap(nums[fa], nums[fb]);
                fa++;
                fb++;
            }
            else if(nums[fb]==2)
            {
                swap(nums[fb], nums[fc]);
                fc--;
            }
            else
            {
                fb++;
            }
        }
        return;  
    }
};

思考

  • 算法时间复杂度为O(\(n\)),空间复杂度为O(\(1\) )。
  • 题目要求一次遍历,in-place完成,采用三指针,首尾两个指针,中间一个指针。中间指针取到1时,往后移动,如果为0,则和首指针互换,首指针和中间指针均往后移一位。如果为2,则和尾指针互换,尾指针向前移一位。当中间指针移动到比尾指针还大时跳出循环。

转载于:https://www.cnblogs.com/zuotongbin/p/10512395.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值