How to realize color classification by brushing leetcode sliding window with golang
This article mainly shows you "golang brush leetcode sliding window how to achieve color classification", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "golang brush leetcode sliding window how to achieve color classification" this article.
Given an array of n elements of red, white, and blue, sort them in place so that the elements of the same color are adjacent and arranged in red, white, and blue order.
In this question, we use integers 0, 1, and 2 to represent red, white, and blue, respectively.
Note:
You cannot use the sort function in the code base to solve this problem.
Example:
Input: [2pence0pence2jue 1jor0] output: [0pj0pje 1pje 1je 2jue 2]
Advanced:
An intuitive solution is to use a count-sorted two-pass scan algorithm.
First, iterate to 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 come up with an one-trip scanning algorithm that only uses constant space?
Ideas for solving the problem:
This problem is called the Dutch flag problem.
Originally proposed by Edsger W. Dijkstra.
The main idea is to set a color for each number and adjust it according to the order of the colors of the Dutch flag.
We use three pointers (p0, p2, and curr) to track the rightmost boundary of 0, the leftmost boundary of 2, and the currently considered element, respectively.
The idea of this solution is to move the curr pointer along the array. If nums [curr] = 0, it will be exchanged with nums [p0]; if nums [curr] = 2, it will be exchanged with nums [p2].
Arithmetic
The rightmost boundary of initialization 0: P0 = 0. During the whole execution of the algorithm, nums [idx]
< p0] = 0. 初始化2的最左边界 :p2 = n - 1。在整个算法执行过程中 nums[idx >P2] = 2. Initialize the currently considered element sequence number: curr = 0.
While curr