Sort Colors

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?

首先复习一下基础知识:

1,类的实例化: inst=className();即类名+(),如本题,实例化方法为:inst=Solution()

2,if...eles if的表达方式不是c++那种表达方式,eles  if在python中表述为elif

3,python有严格的缩进要求,不然就会报错,及时是使用注释'''或#也要缩进

程序测试的时候,当测试数组为[2]的时候,报错while nums[end]==2: list index out of range,可我感觉下标没错,还需要认真的检查一下吧,

为了避免这个问题,我加了了 if lenth==1。

class Solution:
    # @param {integer[]} nums
    # @return {void} Do not return anything, modify nums in-place instead.
    def sortColors(self, nums):
        lenth=len(nums)
        start=0
        end=lenth-1
        while nums[start]==0:
            start+=1
            if start==lenth:
                return 
            
        movePs=start
        while nums[end]==2:
            if end==0:
                return
            end-=1
        while movePs<=end:
            if nums[movePs]==0:
                temp=nums[start]
                nums[start]=nums[movePs]
                nums[movePs]=temp
                start+=1
                movePs+=1
            elif nums[movePs]==1:                     
                movePs+=1
            else:
                '''这是等于2的情况'''
                temp=nums[end]
                nums[end]=nums[movePs]
                nums[movePs]=temp
                end-=1
        return 
                    
                
原文地址:https://www.cnblogs.com/qiaozhoulin/p/4567136.html