LeetCode Brushing Notes _75. Color Classification

The topic is from LeetCode

75. Color Classification

Other solutions or source code can be accessed: tongji4m3

description

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:

输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]

Advanced:

An intuitive solution is to use a two-pass scanning algorithm for counting sorting.
First, iteratively calculate the number of elements 0, 1, and 2, and then rewrite the current array in the order of 0, 1, and 2.
Can you think of a one-pass scanning algorithm that uses only constant space?

Ideas

Using the partition idea of ​​fast sorting, define pointers at the beginning and end of the array, lo identifies the end of 0 (guarantee that lo-1 must be 0), and hi identifies the beginning of 2 (guarantee that hi+1 must be 2). Then use pointer i. Iterate over the array

A better test case2 0 1 0 1 2

Code

public void sortColors(int[] nums)
{
    
    
    int lo=0,hi=nums.length-1;
    int i=0;
    while(i<=hi)
    {
    
    
        if(nums[i]==0)
        {
    
    
            //exch(nums,i++,lo++); 由于特殊性,化简
            nums[i++] = nums[lo];
            nums[lo++] = 0;
        }
        else if(nums[i]==1)
        {
    
    
            ++i;
        }
        else
        {
    
    
            //                exch(nums,i,hi--);
            nums[i] = nums[hi];
            nums[hi--] = 2;
        }

    }
}

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108333165