Sort Colors - LeetCode
题目:
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.
分析:在这道题目中,我们使用三个指针,begin负责确定0,初始指向数组最后一个元素,last负责确定2,初始指向数组最后一个元素,而i负责循环这个数组。当i == 2时,将i与last互换,last向前移,此时我们不能移动i ,因为last原先指向的有可能就是2,所以我们需要在下一次判断才能决定i是否向后移;而i == 0时,将i与begin互换,begin像后移,i也向后移,因为此时的i指向什么数字,在后面循环时都能弥补。直到i与last相等时,i指向了1的右边缘。此时sort完成。过程有些像快排。
代码:
class Solution:
# @param A a list of integers
# @return nothing, sort in place
def sortColors(self, A):
if not A:
return
begin = 0
last = len(A)-1
i = 0
while i <= last:
if A[i] == 0:
A[i],A[begin] = A[begin],A[i]
i+=1
begin += 1
elif A[i]==2:
A[i],A[last] = A[last],A[i]
last-=1
else:
i+=1