Leetcode练习(Python):数组类:第75题:给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。

题目:第75题:给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。  此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。  注意: 不能使用代码库中的排序函数来解决这道题。  
思路:
思路较简单,提示了进阶思路

进阶:

一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?

程序1:

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        if length <= 0:
            return nums
        if length == 1:
            return nums
        num_0 = 0
        num_1 = 0
        num_2 = 0
        for index1 in range(length):
            if nums[index1] == 0:
                num_0 += 1
            elif nums[index1] == 1:
                num_1 += 1
            elif nums[index1] == 2:
                num_2 += 1
        for index2 in range(0, num_0):
            nums[index2] = 0
        for index3 in range(num_0, num_0 + num_1):
            nums[index3] = 1
        for index4 in range(num_0 + num_1, length):
            nums[index4] = 2
常数空间的方法:
这个超时了,之后的按照这个思想来改进
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        if length <= 0:
            return nums
        if length == 1:
            return nums
        index1 = 0
        while index1 < length:
            if nums[index1] == 0:
                del nums[index1]
                nums = [0] + nums
                index1 += 1
            elif nums[index1] == 2:
                del nums[index1]
                nums = nums + [2]
                index1 = index1
            elif nums[index1] == 1:
                index1 += 1
        #return nums
改进的方法:
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        num_0 = 0
        num_2 = length - 1    
        index = 0
        while index <= num_2:
            if nums[index] == 0:
                nums[index], nums[num_0] = nums[num_0], nums[index]
                num_0 += 1
            elif nums[index] == 2:
                nums[index], nums[num_2] = nums[num_2], nums[index]
                index -= 1    
                num_2 -= 1
            index += 1
原文地址:https://www.cnblogs.com/zhuozige/p/12759545.html