Leetcode 题解 -- 排序--荷兰国旗问题

本文探讨了荷兰国旗问题的两种排序算法,一种是通过记录每种颜色数量的暴力解法,另一种是使用双指针的高效解法,旨在将红、白、蓝三色球按颜色顺序正确排列。

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

荷兰国旗问题

1.暴力解法 记录每个的个数

2. 双指针 中间的

荷兰国旗包含三种颜色:红、白、蓝。

有三种颜色的球,算法的目标是将这三种球按颜色顺序正确地排列。

它其实是三向切分快速排序的一种变种,在三向切分快速排序中,每次切分都将数组分成三个区间:小于切分元素、等于切分元素、大于切分元素,而该算法是将数组分成三个区间:等于红色、等于白色、等于蓝色。

 

 

按颜色进行排序

75. Sort Colors (Medium)

 

[LeetCode] Sort Colors 颜色排序

 

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.

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

Example:

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

Follow up:

    • A rather straight forward solution is a two-pass algorithm using counting sort.
      First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
    • Could you come up with a one-pass algorithm using only constant space?

 

 

这道题的本质还是一道排序的题,题目中给出提示说可以用计数排序,需要遍历数组两遍,那么先来看这种方法,因为数组中只有三个不同的元素,所以实现起来很容易。

- 首先遍历一遍原数组,分别记录 0,1,2 的个数。
- 然后更新原数组,按个数分别赋上 0,1,2。

class Solution {
public:
    void sortColors(vector<int>& nums) {
        vector<int> colors(3);
        for (int num : nums) ++colors[num];
        for (int i = 0, cur = 0; i < 3; ++i) {
            for (int j = 0; j < colors[i]; ++j) {
                nums[cur++] = i;
            }
        }
    }
};

题目中还要让只遍历一次数组来求解,那么我需要用双指针来做,分别从原数组的首尾往中心移动。

- 定义red指针指向开头位置,blue指针指向末尾位置。

- 从头开始遍历原数组,如果遇到0,则交换该值和red指针指向的值,并将red指针后移一位。若遇到2,则交换该值和blue指针指向的值,并将blue指针前移一位。若遇到1,则继续遍历。

你要考虑收尾的情况 让他们也参与依次比较 而且 blue是不断变化的只要blue到了就不用比较了

class Solution {
    public void sortColors(int[] nums) {
        int red = 0, blue = nums.length -1;
        for(int i=0; i<= blue; i++){
            if(nums[i] == 0)
                swap(nums, red++, i);
            else if(nums[i] == 2){
                swap(nums, blue--,i--);
            }
        }
    }
    private void swap(int[] nums, int i, int j){
        int t = nums[i];
        nums[i] =nums[j];
        nums[j] = t;
        
    }
}

当然我们也可以使用 while 循环的方式来写,那么就需要一个变量 cur 来记录当前遍历到的位置,参见代码如下:

 

解法三:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int left = 0, right = (int)nums.size() - 1, cur = 0;
        while (cur <= right) {
            if (nums[cur] == 0) {
                swap(nums[cur++], nums[left++]);
            } else if (nums[cur] == 2) {
                swap(nums[cur], nums[right--]);
            } else {
                ++cur;
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值