Sort Colours
Medium · two pointers
A row of flags is stored as a list nums. Each flag has one of three colours, written as the numbers 0 (red), 1 (white) and 2 (blue).
Return a new list with the same flags arranged so that all the 0s come first, then all the 1s, then all the 2s. That is the list in ascending order.
Do not use a library sort (such as sort, sorted or Arrays.sort) to do it.
The input list is not changed, and the answer has exactly as many of each value as the input does.
Examples
Example 1
Input: nums = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Two reds, two whites and two blues, in that order.
Example 2
Input: nums = [1, 2, 0]
Output: [0, 1, 2]
Example 3
Input: nums = [2, 2, 2]
Output: [2, 2, 2]
Only one colour is present, so nothing moves.
Constraints
- 1 <= len(nums) <= 10^4
- nums[i] is 0, 1 or 2.