Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
题目大意: 给定一个长度为n的数组,该数组所有值表示的是红色、白色、黄色,分别用0,1,2来表示。现在需要将数组按照红色、白色、黄色来排列。规定不能使用库的排序函数实现。
解题思路:最简单的方法就是遍历一遍数组,得到0、1、2的个数a、b、c,然后再重新遍历一遍数组,前a个数赋值为0,接下来的b个数赋值为1,最后c个数赋值为2.但是后面题目补充要求是只遍历一遍数组。
只能采用一种新的思路。该思路是在遍历数组的时候就把每个数放置到合适的位置上去。用left、right两个指针来表示从左边到left-1这个位置的数都为0以及从右边到right+1这个位置的数都为2。
遍历数组,如果碰到了数字0,则把nums[i]和nums[left]调换,如果碰到了数字2,则把nums[i]和nums[right]调换,如果碰到数字1就继续遍历。
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums == []:
return()
left = 0
right = len(nums) - 1
i = 0
while i <= right:
if nums[i] == 2:
nums[i], nums[right] = nums[right], nums[i]
right -= 1
elif nums[i] == 0:
nums[i], nums[left] = nums[left], nums[i]
left += 1
i += 1
else:
i += 1