Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library’s sort function.
Example 1:
1 | Input: nums = [2,0,2,1,1,0] |
Example 2:
1 | Input: nums = [2,0,1] |
Constraints:
1 | n == nums.length |
Approach
1 | Use two pointers to keep 0 and 2 at the beginning and the end of the array. |
Algorithm
1 | 1. Go through the list. If encounter 2, swap the current element and the right element. Move the right pointer to the left. |
Implementation
1 | void swap(int* nums, int x, int y) { |