LeetCode 75 SortColor(Python详解及实现)

来源:互联网 发布:单片机的最小系统 编辑:程序博客网 时间:2024/04/29 14:37

【题目】

Given an array with n objects colored red,white or blue, sort them so that objects of the same color are adjacent, withthe colors in the order red, white and blue.

 

Here, we will use the integers 0, 1, and 2to represent the color red, white, and blue respectively.

 

Note:

You are not suppose to use the library'ssort function for this problem.

 

click to show follow up.

 

Follow up:

A rather straight forward solution is atwo-pass algorithm using counting sort.

First, iterate the array counting number of0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's andfollowed by 2's.

 

Could you come up with an one-passalgorithm using only constant space?

 

给定n个颜色,红色,白色和蓝色。分别用0,1,2代替,将这些颜色排序,0在1前,1在2前。

注意:

不允许使用库函数。

遍历两遍数组,第一遍对0,1,2计数,第二遍对数组进行赋值。想出一种方法只使用常数空间,而且只能遍历一遍

【思路】

 设置两个头尾指针,头指针pHead指向的位置是0该放置的位置,尾指针pTail指向的位置是2该放置的位置。i用来遍历整个数组,碰到0把它和pHead指向的数交换,碰到2把它和pTail指向的数交换,碰到1继续向后遍历。有点类似快速排序的分割数组这一步。

 

【Python实现】

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

       pHead = 0

       pTail = len(nums) - 1

       i = 0

       while i <= pTail :

           if nums[i] == 2:

                nums[i], nums[pTail ] = nums[pTail], nums[i]

                pTail  -= 1

           elif nums[i] == 0:

                nums[i], nums[pHead] =nums[pHead], nums[i]

                pHead += 1

                i += 1

           else:

                i += 1

       #print(nums)

 

 

if __name__ == '__main__':

    S= Solution()

   matrix =[1,2,0,2,1,0,0,2,1,1,0]

   S.sortColors( matrix)

                   

 

阅读全文
0 0
原创粉丝点击