[leetcode] Sort Colors

来源:互联网 发布:行知教育基地 编辑:程序博客网 时间:2024/06/06 05:35

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.

click to show follow up.

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?

思路:

用类似quicksort的方法,进行一次遍历,在遍历过程中,遇到0就放在前面,遇到2就放在后面,然后把1夹在中间,从而成功排序

class Solution:    # @param A a list of integers    # @return nothing, sort in place    def swap(self, index1, index2, A):        tmp = A[index1]        A[index1] = A[index2]        A[index2] = tmp            def sortColors(self, A):        start = 0        end = len(A) - 1        while start < len(A) and A[start] == 0:            start += 1        while end >= 0 and A[end] == 2:            end -= 1        index = start        while index <= end:            if A[index] == 0:                self.swap(start, index, A)                start += 1                if start > index:                    index = start            elif A[index] == 1:                index += 1            elif A[index] == 2:                self.swap(index, end, A)                end -= 1                if A[index] == 0:                    self.swap(start, index, A)                    start += 1                    if start > index:                        index = start


0 0