LeetCode Sort Colors
LeetCode-solving Sort Colors
Original question
An array composed of three colors: red, white, and blue. The elements of the same color are put together in the red, white, and blue order. 0 indicates red, 1 indicates white, and 2 indicates blue. This is also known as the Dutch flag.
Note:
Traverse only once as much as possible
Example:
Input: nums = [1, 2, 1, 2, 0, 2, 1, 0, 2]
Output: [0, 0, 0, 0, 1, 1, 1, 2, 2, 2]
Solutions
If there are only two colors, it is easy to think of the first and last two pointers traversing the middle. If the color is incorrect, the positions are exchanged. Three colors can still be used to do this, but one more pointer is required. The first and second pointers are used to separate the arranged red and blue, and the middle pointer is used to traverse the elements:
If it is red, it will be exchanged with the front pointer, and the two will move to the back. The front pointer must be white, because the pointer has scanned those elements. If it is white, if it is blue, it is switched to the back pointer. The back pointer moves forward, and the middle pointer cannot move backward, because we are not sure what color the element is. AC source code
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ left = mid = 0 right = len(nums) - 1 while mid <= right: if nums[mid] == 0: nums[mid], nums[left] = nums[left], nums[mid] left += 1 mid += 1 elif nums[mid] == 1: mid += 1 else: nums[mid], nums[right] = nums[right], nums[mid] right -= 1if __name__ == "__main__": l = [1, 2, 1, 2, 0, 2, 1, 0, 2, 0, 0, 2] Solution().sortColors(l) assert l == [0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2]