LeetCode 75 Color Classification The LeetCode Road of Heroding

Given an array of n elements containing red, white, and blue, sort them in place so that the elements of the same color are adjacent and arranged in the order of red, white, and blue.

In this question, we use integers 0, 1, and 2 to represent red, white, and blue, respectively.

Note:
You cannot use the sorting function in the code base to solve this problem.

Example:

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

Advanced:

一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?

Problem-solving ideas:
Just see the problem, then naturally use the sorting algorithm! Is sort not fragrant? Ever since:

class Solution {
    
    
public:
    void sortColors(vector<int>& nums) {
    
    
        sort(nums.begin(), nums.end());
    }
};

The submission was also correct. I was dumbfounded when I looked at it carefully. I didn’t use the class library. I had to sort it by myself. So I thought of a different idea, which is to count the numbers of 0, 1, and 2 and then re-accord them. Just assign the number to nums, the code is as follows:

class Solution {
    
    
public:
    void sortColors(vector<int>& nums) {
    
    
        int len = nums.size();
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        for(int i = 0; i < len; i ++){
    
    
            if(nums[i] == 0){
    
    
                num1 ++;
            }
            if(nums[i] == 1){
    
    
                num2 ++;
            }
            if(nums[i] == 2){
    
    
                num3 ++;
            }
        }
        vector<int> v1(num1, 0);
        vector<int> v2(num2, 1);
        vector<int> v3(num3, 2);
        v1.insert(v1.end(),v2.begin(), v2.end());
        v1.insert(v1.end(),v3.begin(), v3.end());
        nums = v1;
    }
};

The next idea is similar

class Solution {
    
    
public:
    void sortColors(vector<int>& nums) {
    
    
        int len = nums.size();
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        for(int i = 0; i < len; i ++){
    
    
            if(nums[i] == 0){
    
    
                num1 ++;
            }
            if(nums[i] == 1){
    
    
                num2 ++;
            }
            if(nums[i] == 2){
    
    
                num3 ++;
            }
        }
        for(int i = 0; i < len ; i ++){
    
    
            if(num1 > 0){
    
    
                nums[i] = 0;
                num1 --;
                continue;
            }
            if(num2 > 0){
    
    
                nums[i] = 1;
                num2 --;
                continue;
            }
            if(num3 > 0){
    
    
                nums[i] = 2;
                num3 --;
                continue;
            }
        }
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108946815