Sort Colors
Given an array with n objects colored red (0), white (1), or blue (2), sort them in-place so same colors are adjacent in order 0, 1, 2.
The function modifies nums in place and returns nothing; the tests print the sorted nums space-separated.
Example
2,0,2,1,1,0
0 0 1 1 2 2
- The input
2,0,2,1,1,0is a list of colour codes: = red, = white, = blue. Each value is only a label, so the task is grouping, not general ordering. - Tally the colours: red appears times (positions and ), white times (positions and ), blue times (positions and ). The total is .
- Rearranging never creates or destroys a value, so the result must hold exactly those tallies: reds fill positions to , whites positions to , blues positions to .
- That gives
0 0 1 1 2 2, the same six numbers in non-decreasing order, printed space-separated. - Notice that "in-place" means the list passed in is itself changed: after the call,
numsholds the grouped order, and nothing needs to be returned. With reds and whites, the blues always start at position .
Constraints
- 1 <= len(nums) <= 300
- nums[i] is 0, 1, or 2