The method of scanning the array twice is: calculate the number of each color in the first time, and then assign all colors back to the array in the second time.
Scan the array once:
Records the next position of three colors in the nextpos Array
Consider how to update nextpos when a = {, 0}
Initial: nextpos = {0, 0}
The first color is 0, so nextpos [0] = 1. A = {0...} but because 1 and 2 must be behind 0, nextpos [1] and nextpos [2] are both 1
The second color is 2, so nextpos [2] = 2. A = {0, 2...} 1 and 0 are both in front of 2, so no other values need to be updated.
The third color is 1, nextpos [1] ++, and the value is 2. At the same time, we should move 2 back to one place. A is {0, 1, 2 ...}. Nextpos [2] = 3.
The fourth color is 1, nextpos [1] ++, and the value is 3. 2. You have to move another one back. nextpos [2] = 4.
The last color is 0, so a [1] = 0. All other colors must be moved one by one. A [3] = 1, a [4] = 2. Nextpos [1] = 4, nextpos [2] = 5.
After observation, we can find that the current color is color = A [I]. We need to move all the colors greater than the color back, and the corresponding nextpos ++
You can write it in one sentence:
for (int c = A[i]; c < 3; c++) A[nextPos[c]++] = c;
When I = 0, nextpos is changed to {1, 1, 1}, but a [0] is changed to 2. So we need to reverse the for loop so that a [0] is still 0
for (int c = 2; c >= A[i]; c--) A[nextPos[c]++] = c;
However, this loop does not run correctly, because when C = 2, a [0] is changed to 2, c -- <2, and the loop ends. So we need to use another variable to record the initial value of a [I] And get the final program:
void sortColors(int A[], int n) { int nextPos[3] = {0}; for (int i = 0; i < n; i++) { int color = A[i]; for (int c = 2; c >= color; c--) A[nextPos[c]++] = c; }}
Sort colors [leetcode] scans the array once, and solves the space complexity of O (1 ).