Sort Colors
Given an array nums with n objects colored red, white, or blue and represented by the integers 0, 1, and 2, sort them in-place so that objects of the same color are adjacent, in the order red (0), white (1), then blue (2). You must solve it without using the library sort function.
Open official problem prompt ↗Rearrange an array of 0s, 1s, and 2s into sorted order in a single pass, mutating the array in place.
Sorting a mixed pile of red, white, and blue socks by hand: red socks go to the far left, blue socks to the far right, and whites naturally settle in the middle as you sweep across the pile once.
- Input
- nums = [2, 0, 2, 1, 1, 0]
- Output
- [0, 0, 1, 1, 2, 2]
- Why
- The two 0s come first, then the two 1s, then the two 2s.
n == nums.length1 <= n <= 300nums[i] is either 0, 1, or 2Follow-up: solve in one pass with O(1) extra space