212. Sort Colors
Medium
Dutch National Flag
Array
Problem
Given an array nums containing only 0, 1 and 2, sort the values in-place so equal values are adjacent and ordered 0, 1, 2. Return the sorted array.
Examples
Example 1
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2
Input: [2,0,1]
Output: [0,1,2]
Example 3
Input: [0]
Output: [0]
Constraints
� 1 <= nums.length <= 300
� nums[i] is 0, 1 or 2.
Hints
?? Maintain regions for confirmed zeroes and confirmed twos.
?? The current pointer scans the unknown region.
Expected Complexity
Time: O(n)
Space: O(1)
Follow-up
Can you solve it in one pass using constant extra space?
Practice Notes
Attempts: 0
Time spent: 0min
Hints used: 0
JavaScript
00:00
Loading...
Case 1
Case 2
Case 3
Input
[2,0,2,1,1,0]Expected
[0,0,1,1,2,2]