75. 颜色分类

    科技2024-05-10  91

    题目

    给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

    此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

    注意: 不能使用代码库中的排序函数来解决这道题。

    示例:

    输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2]

    代码

    class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i = 0 j = len(nums)-1 index = 0 while index <= j: if nums[index] == 0: nums[i],nums[index] = nums[index],nums[i] i += 1 index += 1 elif nums[index]==2: nums[j],nums[index] = nums[index],nums[j] j -= 1 else: index += 1
    Processed: 0.021, SQL: 8