Likou 75. Color Classification-C Language Implementation-Medium Difficulty Questions

topic

Portal

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.

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [0]
Output: [0]

Example 4:

Input: nums = [1]
Output: [1]

prompt:

n == nums.length
1 <= n <= 300
nums[i] 为 0、1 或 2

Source: LeetCode

Problem solving

template

void sortColors(int* nums, int numsSize){
    
    

}

analysis

According to find a different thinking understanding, because this question asks for the order of red, white and blue to arrange the colors as close as possible, and this order happens to be the order of 012 instead, then we can simply understand the following questions It means to arrange the array elements as needed, so that it can also be arranged in the order of the elements and be as close together as possible to meet the requirements of the problem.

Original code

int cmp(int *a, int *b) {
    
    
    return *a - *b;
}
void sortColors(int* nums, int numsSize){
    
    
        qsort(nums, numsSize, sizeof(int), cmp);
    return nums;
}

qsort is a sorting function in C language. It has also been used in the topic of array splitting . If you are interested, you can take a look at the introduction to the simple use of qsort()

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44922487/article/details/113832735